Link to home
Start Free TrialLog in
Avatar of Bob Hoffman
Bob HoffmanFlag for United States of America

asked on

MS SQL Update one row from many rows

Run the attached script.

Why is field val_1 in #table1 = 100.00? I'm expecting 600.00. Any suggestions? Thanks
CREATE TABLE [dbo].[#table1](
	[_key] [int],
	[val_1] [money])
 
CREATE TABLE [dbo].[#table2](
	[_key] [int],
	[val_2] [money])
 
INSERT INTO #table1 VALUES (1,0)
INSERT INTO #table2 VALUES (1,100.00)
INSERT INTO #table2 VALUES (1,200.00)
INSERT INTO #table2 VALUES (1,300.00)
 
UPDATE #table1
	SET val_1 = IsNull(val_1,0) + IsNull(val_2,0) 
FROM #table2  
WHERE #table2._key = #table1._key
 
SELECT * FROM #table1
 
DROP TABLE #table1
DROP TABLE #table2

Open in new window

SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg 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
ASKER CERTIFIED SOLUTION
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 Bob Hoffman

ASKER

Both suggestions worked. Because my actual UPDATE has 36 fields that need to be updated BrandonGalderisi solution seemed to be the better way to go. Thanks