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

LVL 8
Bob HoffmanDeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
because you don't do the sum:
UPDATE #table1
   SET val_1 = IsNull(val_1,0) + (SELECT SUM(IsNull(val_2,0) FROM #table2 WHERE #table2._key = #table1._key )

Open in new window

0
BrandonGalderisiCommented:
Because youre result is evaluated on a line by line bases.  Run the select. and you'll see.  try this:


Swap:

UPDATE #table1
        SET val_1 = IsNull(val_1,0) + IsNull(val_2,0)
FROM #table2  
WHERE #table2._key = #table1._key

With:


UPDATE t1
 
        SET val_1 = IsNull(val_1,0) + IsNull(val_2,0) 
FROM #table1 t1
join (select _key,sum(val_2) from #table2 group by _key) t2
on t1._key = t2._key

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bob HoffmanDeveloperAuthor Commented:
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
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.