I have stored procedure that take @dbName and insert record in that DB.
I want to get the id of the last inserted record. SCOPE_IDENTITY() returns NULL and @@IDENTITY returns correct id, why it happens? As I read, so it’s better to use SCOPE_IDENTITY() in case there are some triggers on the table.
Can I use IDENT_CURRENT? Does it return the id in the scope of the table, regardless of trigger?
So what is the problem and what to use?
EDITED
DECALRE @dbName nvarchar(50) = 'Site'
DECLARE @newId int
DECLARE @sql nvarchar(max)
SET @sql = N'INSERT INTO ' + quotename(@dbName) + N'..myTbl(IsDefault) ' +
N'VALUES(0)'
EXEC sp_executesql @sql
SET @newId = SCOPE_IDENTITY()
Like Oded says, the problem is that you’re asking for the identity before you execute the
insert.As a solution, it’s best to run
scope_identityas close to theinsertas you can. By usingsp_executesqlwith an output parameter, you can runscope_identityas part of the dynamic SQL statement:Here’s an example at SE Data showing that
scope_identityshould be inside thesp_executesql.