Hi,
I was wondering if you can help.
I am running an sql query that creates several new records based on a select query. In other words duplicating some existing records in a table.
What I need to do is after I have created these new records update a field in each of them.
Any ideas how I can retrieve all of their ids at insertion and then use them to update a field in each of them?
Ideally I would like to use @.@.identity and datareaders with vb.net.
Cheers
Mark :)
You need to put all the TSQL into a stored procedure. After each insert use SCOPE_IDENTITY() to get the id of the record just inserted.
DECLARE @.batchid uniqueidentifier
SELECT @.batchid=newid()
--The insert
INSERT INTO table (column1,column2 ..... , batchid)
SELECT column1,column2......, @.batchid FROM table WHERE...
--Retrieve the new id:s
SELECT id FROM table WHERE batchid=@.batchid
But it's quite likely that you can insert the correct data directly, instead of having to update it afterwards.
INSERT INTO table (column1,column2 ..... , column15)
SELECT column1,column2......, @.thenewvalueforcolumn15 FROM table WHERE...|||
Although I like the solution of gunteman, I'm just wondering why you can't update the field in the INSERT statement?
|||Hi,
Thanks for your help. But i would really like to update the field in the insert statement.
Any suggestions?
Cheers
Mark :)
|||I described it above. If you want to set the new value directly, just include it in your insert statement.
INSERT INTO table (column1,column2 ..... , column15)
SELECT column1,column2......, @.thenewvalueforcolumn15 FROM table WHERE...
If you show us your INSERT and UPDATE statement, we could help you combine them.
No comments:
Post a Comment