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 2005 Forums
 Transact-SQL (2005)
 Select rows then update them before re-inserting

Author  Topic 

dkekesi
Starting Member

38 Posts

Posted - 2011-07-27 : 02:36:46
Dear Everyone,

I have several records that I query with a simple select statement. What I wish is to update a single column before re-inserting the dataset back into the same table. Basically copying rows and updating a FK column.
Take the following table (DocID is the FK):
ID Name DocID Data1 Data2 Data3
1 lala1 1 aaa bbb ccc
2 lala2 1 bbb ccc ddd
3 lala3 1 ccc ddd eee
4 lala4 2 ddd eee fff

I wish to select all rows where DocID=1 then update the selected data to set DocID=3 and insert them back into the table. The End result should be like this:
ID Name DocID Data1 Data2 Data3
1 lala1 1 aaa bbb ccc
2 lala2 1 bbb ccc ddd
3 lala3 1 ccc ddd eee
4 lala4 2 ddd eee fff
1 lala1 3 aaa bbb ccc
2 lala2 3 bbb ccc ddd
3 lala3 3 ccc ddd eee

How would I approach this problem? Any help is most appreciated.
Thank you for your time.

Best Regards,
Daniel

Best Regards,
Daniel

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2011-07-27 : 03:20:51
insert YourTable(ID Name DocID Data1 Data2 Data3)
select
ID,
Name,
3 as DocID,
Data1,
Data2,
Data3
from YourTable
where DocID = 1



No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

dkekesi
Starting Member

38 Posts

Posted - 2011-07-27 : 05:04:02
OK, I'm feeling a little stupid now. I should use the thing on my neck before asking silly questions.
Thanks again.

quote:
Originally posted by webfred

insert YourTable(ID Name DocID Data1 Data2 Data3)
select
ID,
Name,
3 as DocID,
Data1,
Data2,
Data3
from YourTable
where DocID = 1



No, you're never too old to Yak'n'Roll if you're too young to die.



Best Regards,
Daniel
Go to Top of Page
   

- Advertisement -