DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
SITE SEARCH SQLUSA.com HEADLINES NEWS
SQL E/BOOKS   SQL 2014 PROGRAMMING   DOWNLOADS
SCRIPTS SQL 2005 SQL 2008 ARTICLES
SQL JOBS TWITTER FORMAT VIDEOS
How to capture IDENTITY values assigned in INSERT?

Execute the following Microsoft SQL Server T-SQL script in Management Studio Query Editor to demonstrate capturing a single assigned IDENTITY or a range of IDENTITY values using the OUTPUT clause.

 

USE tempdb;

CREATE TABLE Employee

(

 idnum int IDENTITY(1,1),

 fname varchar (20),

 minit char(1),

 lname varchar(30)

);

 

INSERT Employee    (fname, minit, lname)

VALUES    ('Elvis', 'A', 'Presley');

 

INSERT Employee   (fname, minit, lname)

VALUES   ('Frank', 'A', 'Sinatra');

GO

DECLARE @IDrange TABLE (ID int, Seq int identity(1,1),

                        Dstamp datetime default (CURRENT_TIMESTAMP));

DECLARE @i int = 0;

WHILE (@i < 5)

BEGIN

  INSERT Employee(fname, minit, lname)

  OUTPUT inserted.idnum INTO @IDrange(ID)

  SELECT fname, minit, lname

  FROM Employee;

SET @i += 1;

END -- loop

SELECT * FROM @IDrange ORDER BY Seq;

GO

 

DROP TABLE tempdb.dbo.Employee;

------------

 

Exam Prep 70-461
Exam 70-461
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE