Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 select update

Author  Topic 

mshsilver
Posting Yak Master

112 Posts

Posted - 2014-04-07 : 09:18:29
Hi,
I am doing a basic select from one table and update the vales from the selected table into another based on a matching unique key. That works fine. See below an example.

update t1 set t1.field1 = t2.field1, t1.field2 = t2.field2 etc. etc.
from t1
inner join t2 on t1.uniqueid =t2. uniqueid

What I need to tackle is: If t1.field1 has a value in it and t2.field1 does not, I do not want to overwrite t1.field1 with a null value. So I just want to bring t2 fields over with values otherwise ignore them.

Question is, am I going to have to have an update statement per field? There are about 30+ fields.... I figured there must be a cleaner way of doing this in a single query.

Any advice on this would be much appreciated. Thanks for looking.

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2014-04-07 : 09:28:19
set t1.field=isnull(t2.field,t1.field)


Too old to Rock'n'Roll too young to die.
Go to Top of Page

stepson
Aged Yak Warrior

545 Posts

Posted - 2014-04-07 : 09:28:35
one way:


update t1 set t1.field1 =

case when t2.field1 is null then t1.field1
else t2.field1 end

etc...






sabinWeb MCP
Go to Top of Page

mshsilver
Posting Yak Master

112 Posts

Posted - 2014-04-07 : 10:15:50
Perfect, thank you for both your replies. I am sure i can get what i need working from this, it's good to talk! Appreciate your help.
Go to Top of Page
   

- Advertisement -