June 3, 2014 at 6:56 pm
Hi,
I have a 2table like
create table test1
(col1 identity(1,1),
col2 varchar(20)
)
create table test2
(old int,
new int)
Existing record in test1 table
(1,'test')
Now i want to insert a new record into test1 and then capture the old and new identity columsn in test 2 table
i.e. after insert test1 table will be
1,test
2,test
and test2 table will be like
1,2 -- old and new identity columns are captured during insert and stored in test2 table.
If the repeat the process again test2 table will be like
1, test
2,test
3, test
and test2 table will be
2,3 --- test2 table will always have only one record. old records will be deleted.
Using output clause i can get the new identity value.. but how can i get the old identity value and insert that into test2 table..
I am not willing to do a self join after the record is inserted into test2. I wanted to get the old ident value during insert of new ident value.
I appreciate your responses.
June 3, 2014 at 7:34 pm
Why not do something like this? I did not have SSMS in front me to test, it was done in notepad. Hope this helps or gets you on the right path.
DECLARE @OLDID INT, @NEWID INT
SET @OLDID = ( SELECT MAX(COL1) FROM TEST1 )
INSERT INTO TEST1
SELECT 1, TEST
UNION ALL
SELECT 2, TEST
UNION ALL
SELECT 3 TEST
UNION ALL
SELECT 4, TEST
SET @NEWID = SCOPEIDENTITY()
INSERT INTO TEST2
SELECT @NEWID, TEST
UNION ALL
SELECT @OLDID, TEST
SET @OLDID = ''
June 4, 2014 at 8:14 am
What a strange requirement. Not sure what you mean by "old" and "new" identity values. Is the "old" value based on the value of col2? If not this seems completely pointless. The identity value here is what allows to uniquely define a row. Can you explain what the reason for this is? Especially since you are going to delete this table and then populate it with the last two inserted values I question why you even need it in a table. Why not just create a view instead?
select top 2 col1
,col2
from test1
order by col1 desc
This is not prone to error and will ALWAYS be accurate.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply