Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Using SCOPE_IDENTITY()

Posted on 2006-07-13
2
Medium Priority
?
804 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 1000 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

Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

719 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