Search
 
SCRIPT & CODE EXAMPLE
 

SQL

sql output inserted id

-- @@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

PREVIOUS NEXT
Code Example
Sql :: oracle character index 
Sql :: sql server pagination 
Sql :: sql select column names 
Sql :: how to open closed port mysql in ubuntu 
Sql :: import sql file in mysql 
Sql :: mqtt Error: Address not available 
Sql :: how to get ddl for materialized view 
Sql :: sql server for loop 
Sql :: date_format for time sql 
Sql :: change month to name in sql server 
Sql :: mysql copy table1 to table2 
Sql :: mysql mediumint max value 
Sql :: update select 
Sql :: oracle sql day of month from date 
Sql :: how to delete table in mysql 
Sql :: if then else sqlite 
Sql :: find most frequent value in sql column 
Sql :: get first 2 letter in sql 
Sql :: mysql number format 
Sql :: mysql round 
Sql :: show tables postgresql 
Sql :: grant all priviledges to mysql user 
Sql :: wsl centos 8 mysql 
Sql :: insert pg result of select 
Sql :: where date major today mysql 
Sql :: tsql cmd exec script from file 
Sql :: how to alter table column name in mysql 
Sql :: MySQL shutdown unexpectedly. 
Sql :: postgresql default value boolean 
Sql :: sql where contains 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =