Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hello,i am executing a couple of inserts in a stored proceedure being called from an insert.However, i would like to know how to retrieve the last inserted auto number value in the same SP, so i could update another table in the same SP.would it be possible to use the set @transctnID = scope_identity() in the SP ?Or do i implement this with a trigger instead ?afrika
tkizer
Almighty SQL Goddess
38200 Posts
Posted - 2004-12-02 : 15:51:58
Yes you would use SCOPE_IDENTITY() to get the value. So here's an example...assume Column1 in Table1 is the identity column.DECLARE @ID intINSERT INTO Table1 (Column2, Column3)VALUES (1, 2)SET @ID = SCOPE_IDENTITY()INSERT INTO Table2 (Column1)VALUES @IDSo we just inserted into Table2 with the value from SCOPE_IDENTIT()HTHTriggers really aren't related here.Tara
Bustaz Kool
Master Smack Fu Yak Hacker
1834 Posts
Posted - 2004-12-04 : 15:35:02
What Tara says here is correct. I just wanted to add one caveat. The SCOPE_IDENTITY() technique works when inserting ONE row of data into the primary table. If you are potentially multiuple rows, you'll need a different approach.HTHLet X = {All sets s such that s is not an element of s}(X element of X) ==> (X not element of X)(X not element of X) ==> (X element of X)(Bertrand Russell Paradox)
afrika
Master Smack Fu Yak Hacker
2706 Posts
Posted - 2004-12-05 : 08:40:40
thanks allAfrika
Hippi
Yak Posting Veteran
63 Posts
Posted - 2004-12-05 : 13:07:15
quote:Originally posted by Bustaz Kool What Tara says here is correct. I just wanted to add one caveat. The SCOPE_IDENTITY() technique works when inserting ONE row of data into the primary table. If you are potentially multiuple rows, you'll need a different approach.HTHLet X = {All sets s such that s is not an element of s}(X element of X) ==> (X not element of X)(X not element of X) ==> (X element of X)(Bertrand Russell Paradox)
Hey folk,Could you post your approach here? I really want to know.Thanks a bunch.
ehorn
Master Smack Fu Yak Hacker
1632 Posts
Posted - 2004-12-05 : 13:37:40
>>Could you post your approach here
create table t ( id int identity(0,1), val char(1))insert into t select 'A' union all select 'B'gocreate proc dbo.up_t_insert @val char(1), @id int outputasset nocount on insert t (val) select @val select @id = scope_identity()returngoselect * from tdeclare @id intexec dbo.up_t_insert 'C', @id outputselect @id as last_id
Bustaz Kool
Master Smack Fu Yak Hacker
1834 Posts
Posted - 2004-12-05 : 17:03:31
-- Set of new primary keysSELECT MyKeyFROM insertedHTH=================================================================It was a woman that drove me to drink... And I never had the decency to thank her.