Solved

Using SCOPE_IDENTITY()

Posted on 2006-07-13
2
799 Views
Last Modified: 2008-02-01
I've got an sp which inserts a record into a table. It does this by building the Sql Statement dynamically and using Exec sp_ExecuteSQL

So my sp looks similar in structure to this:

select @SqlStatment = 'Insert into Table1 (Field2, Field3, Field4) Values(23,98,1212)'
Exec sp_ExecuteSQL @SqlStatement

The table has an identity column for the PrimaryKey. I need to get this value back to use as a foreign key for other Insert statements. So how would I modify the above example to incorporate Select SCOPE_IDENTITY() into it?

Ian
0
Comment
Question by:ipendlebury
2 Comments
 
LVL 10

Accepted Solution

by:
RichardCorrie earned 250 total points
ID: 17100032
you do not need to use scope_identity
use Ident_Current

ie
declare
@newId int
select @SqlStatment = 'Insert into Table1 (Field2, Field3, Field4) Values(23,98,1212)'
Exec sp_ExecuteSQL @SqlStatement

select @newID = Ident_Current('table1')

/Richard
0
 

Author Comment

by:ipendlebury
ID: 17100088
I didn't even know of the existance of Ident_Current(). It works a treat. Thank you.

Ian
0

Featured Post

Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question