Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Perché SCOPE_IDENTITY può restituire NULL mentre @@IDENTITY no?

SCOPE_IDENTITY() può essere NULL in alcuni scenari, mentre @@IDENTITY conserva un valore. Esiste anche un bug noto sulla funzione.

La soluzione più affidabile è usare OUTPUT INTO:

declare @x table (tableID int identity not null primary key, datavalue varchar(10));
declare @y table (tableID int, datavalue varchar(10));

insert into @x (datavalue)
output inserted.tableID, inserted.datavalue
into @y
values ('aaaa');

OUTPUT INTO può catturare più ID e non è soggetto al bug di SCOPE_IDENTITY().