Link to home
Start Free TrialLog in
Avatar of Dale Fye
Dale FyeFlag for United States of America

asked on

SQL Server update query syntax

I'm coming from the Access world, with a lot of experience working with SQL Server via ODBC connections, but am migrating an application to SQL Server and would like to migrate some of the queries over to SQL Stored Procedures.

Background.  I have a staging table in SQL Server, where I'm dumping data from Access and several other data sources.  From that table I have created a view (vw_Cygnet_Tank_Readings_Inches) which pulls in a specific subset of the data from the staging table.

There is a second view (vw_Equipment_Tanks) which joins my Equipment and Tanks tables to provide access to the tank Diameter field based on the EquipID.  I have to join this view to the previous view to associate the Equip_ID field and Diameter field to the tanks identified in the previous view.

I have a destination table in SQL Server (tbl_Readings_Tanks)  which contains about 15 fields, but for the purpose of this question, I need to update two of those fields.  The UPDATE syntax in SQL Server is different in SQL Server than in Access, and I just cannot seem to get this right.
USE WHR_System_Tables

DECLARE @AsOf as datetime2(7)

SELECT @AsOf = NULL

UPDATE tbl_Readings_Tanks 
SET tbl_Readings_Tanks.Inches_End = T.Inches
, tbl_Readings_Tanks.Closing_Vol = (CTRI.Inches/12) * (3.14159 * (ET.Diameter/2) * (ET.Diameter/2)) * 0.17811
FROM (
SELECT ET.Equip_ID
, CTRI.FacilityID
, CTRI.DT_Recorded
, CTRI.Product_ID
, CTRI.TankNum
, CTRI.Inches
, ET.Diameter
, Closing_Vol = (CTRI.Inches/12) * (3.14159 * (ET.Diameter/2) * (ET.Diameter/2)) * 0.17811
FROM  dbo.vw_Equipment_Tanks as ET
INNER JOIN dbo.vw_Cygnet_Tank_Readings_Inches as CTRI
ON ET.DS_PK_Text = CTRI.FacilityID 
AND ET.Product_ID = CTRI.Product_ID 
AND ET.Tank_Num = CTRI.TankNum
WHERE (@AsOf IS NULL) OR (CTRI.Dt_recorded > @AsOf)
) as T
INNER JOIN tbl_Readings_Tanks as RT
ON T.Equip_ID = RT.Equip_ID
AND T.DT_Recorded = RT.docDate
WHERE RT.Inches_End <> T.Inches 

Open in new window

I've declared an @AsOf variable because I will eventually put this in a stored procedure and pass that value as a parameter.  At the moment, it is set to NULL to select all of the records from vw_Cygnet_Tank_Readings_Inches.
ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dale Fye

ASKER

I should have thought of that!

How would I go about getting the number of records updated after running that update query?
Very easy. Use @@ROWCOUNT system function to get the number of affected rows
DECLARE @HowManyRowsUpdated INT
UPDATE table SET value = 1
SELECT @HowManyRowsUpdated = @@ROWCOUNT

Open in new window

Follow-up question here