Search
 
SCRIPT & CODE EXAMPLE
 

SQL

sql get last primary key inserted

-- @@IDENTITY - Returns the last identity created in the same session
-- SCOPE_IDENTITY() - Returns the last identity created in the same session and the same scope
-- IDENT_CURRENT() - Returns the last identity created for a specific table or view in any session
-- OUTPUT Inserted.[ColumnName] INTO [Table] - Returns a list of created identities (used for multi inserts)

/*Examples Start*/
IF OBJECT_ID('tempdb..#tmpT') IS NOT NULL
	DROP TABLE #tmpT

IF OBJECT_ID('TableA') IS NOT NULL
	DROP TABLE TableA

CREATE TABLE TableA (
	ID NUMERIC(18,0) IDENTITY(1,1),
	Name VARCHAR(255),
	PRIMARY KEY (ID)
)

INSERT INTO TableA (Name) VALUES ('Jane')
SELECT @@IDENTITY AS [ID]

INSERT INTO TableA (Name) VALUES ('John')
SELECT SCOPE_IDENTITY() AS [ID]

INSERT INTO TableA (Name) VALUES ('Smith')
SELECT IDENT_CURRENT('dbo.TableA') AS [ID]

DECLARE @NewIds TABLE(ID NUMERIC(18,0))
INSERT INTO TableA (Name)
OUTPUT Inserted.ID INTO @NewIds
VALUES ('Joe'), ('Bloggs')
SELECT * FROM @NewIds

CREATE TABLE #tmpT (ID NUMERIC(18,0))
INSERT INTO TableA (Name)
OUTPUT Inserted.ID INTO #tmpT
VALUES ('Joe'), ('Bloggs')
SELECT * FROM #tmpT
/*Examples End*/
Comment

How to get last inserted primary key in SQL Server

-- 4 ways to get identity IDs of inserted rows in SQL Server

INSERT INTO TableA (...) VALUES (...)
SET @LASTID = @@IDENTITY

INSERT INTO TableA (...) VALUES (...)
SET @LASTID = SCOPE_IDENTITY()

SET @LASTID = IDENT_CURRENT('dbo.TableA')

DECLARE @NewIds TABLE(ID INT, ...)

INSERT INTO TableA (...)
OUTPUT Inserted.ID, ... INTO @NewIds
SELECT ...
Comment

get last inserted primary key

INSERT INTO dbo.Table(columns)
OUTPUT INSERTED.p_key, INSERTED.someothercolumnhere .......
VALUES(...) 
Comment

PREVIOUS NEXT
Code Example
Sql :: sql server get week dates from week number 
Sql :: remove duplicates mysql 
Sql :: end mysql command 
Sql :: alter table name including schema 
Sql :: oracle tablespace autoextend 
Sql :: PG::ForeignKeyViolation: ERROR: update or delete on table violates foreign key constraint 
Sql :: sqlite trim 
Sql :: how to populate a table in MySQL from and existing csv file 
Sql :: grant sql 
Sql :: incorrect datetime value sql table error 1292 
Sql :: sql select without column name 
Sql :: soql last year 
Sql :: while mysql 
Sql :: index in mysql 
Sql :: column with prefix in sql 
Sql :: truncate in oracle sql 
Sql :: select * from 
Sql :: with transaction.atomic(): 
Sql :: decimal to integer sql 
Sql :: sql basic commands 
Sql :: sql query checker 
Sql :: break too long line yaml 
Sql :: mysql isshow 
Sql :: changer un mot de passe mysql 
Sql :: mysqlimport: Error: 4166 
Sql :: java input type sql date 
Sql :: exel bulk insert 
Sql :: cassandra query example 
Sql :: connect colab with Microsoft sql server 
Sql :: APEX elapsed time 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =