Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert select @@Identity

Tags:

sql-server

How to use the @@IDENTITY when I use INSERT SELECT ?

DECLARE @ENTITYID AS BIGINT

INSERT INTO Quiz_QuizQuestion
SELECT @ENTITYID,
       @DIFICULTLEVELCODE,
       ENTITYID,
       @QuizEntityId,
       Title,
       [Description],
       [Description],
       Duration
FROM   Education_Question
WHERE  EntityID = 1 --THIS SELECT RETURN JUST 1 RECORD
SET @ENTITYID = @@IDENTITY

SELECT @ENTITYID // NULL  
like image 496
AFetter Avatar asked Jan 16 '12 12:01

AFetter


2 Answers

You need not insert @@IDENTITY into the table in your scenario - you have to CREATE table with IDENTITY field like this:

CREATE TABLE Quiz_QuizQuestion
(
  EntityId int IDENTITY NOT NULL,
  ...
)
GO

DECLARE @ENTITYID AS BIGINT

INSERT INTO Quiz_QuizQuestion
SELECT 
       @DIFICULTLEVELCODE,
       ENTITYID,
       @QuizEntityId,
       Title,
       [Description],
       [Description],
       Duration
FROM   Education_Question
WHERE  EntityID = 1 --THIS SELECT RETURN JUST 1 RECORD
SET @ENTITYID = SCOPE_IDENTITY()

SELECT @ENTITYID // NULL 
like image 175
Oleg Dok Avatar answered Nov 15 '22 03:11

Oleg Dok


This is copied verbatim from the MSDN page about @@IDENTITY: "After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the last identity value generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL. If multiple rows are inserted, generating multiple identity values, @@IDENTITY returns the last identity value generated." (link). I don't know if you need more information than that.

like image 33
Lamak Avatar answered Nov 15 '22 03:11

Lamak