Solved

Using SCOPE_IDENTITY()

Posted on 2006-07-13
2
802 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

739 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