sql IDENTITY,@@ IDENTITY,SCOPE_IDENTITY(),IDENT_CURRENT(),CREATE SEQUENCE

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql IDENTITY,@@ IDENTITY,SCOPE_IDENTITY(),IDENT_CURRENT(),CREATE SEQUENCE相关的知识,希望对你有一定的参考价值。

/* IDENTITY - property of a column which generates sequential numbers automatically for insertion into table. There are a few ways to query what the last identity created is:

@@IDENTITY - the last identity generated in the current session. Be careful, this will pull the last IDENTITY created in any table. If another IDENTITY has been created subsequently in that session, then it'll pull that IDENTITY and not the one you're expecting.

SCOPE_IDENTITY() - the last identity generated in the current scope. This will make sure you're pulling the IDENTITY that you created, but be careful if there were multiple IDENTITies updated in your batch, you might not get the value you're expecting.

IDENT_CURRENT('table_name') - the last identity inserted into a table, regardless of what session or scope it was created in.

*/

INSERT INTO Sales.Orders (CustomerID, Amount)
VALUES (12, 2056);

SELECT SCOPE_IDENTITY() AS OrderID;

-- Overriding IDENTITY - you can use SET INDENTITY_INSERT to ON in order to allow you to override an IDENTITY restriction and set the number yourself. You probably want to turn this on to make you change, and then turn it off again so that the IDENTITY constraint continues to keep creating unique values.

SET IDENTITY_INSERT SalesLT.CallLog ON;

INSERT INTO SalesLT.CallLog (CallID, SalesPerson, CustomerID, PhoneNumber)
VALUES (9, 'adventureworks, 11, '926-3456')


-- CREATE SEQUENCE - object that creates a sequential value, but are not tied to a single table. For instance, you can have sequential values created for OrderID in your web orders table and also in your retails orders table, therefore creating unique values for OrderID regardless of what table the order lands into.

CREATE SEQUENCE Sales.OrderNumbers AS INT
STARTS WITH 1 INCREMENT BY 1;

...
SELECT NEXT VALUE FOR Sales.OrderNumbers;

以上是关于sql IDENTITY,@@ IDENTITY,SCOPE_IDENTITY(),IDENT_CURRENT(),CREATE SEQUENCE的主要内容,如果未能解决你的问题,请参考以下文章

Reset Identity Column Value in SQL Server (Identity Reset)

sql的identity属性怎么用?

更改 Identity SQL 存储时出错(官方教程)

被 SCOPE_IDENTITY() 和 GO 弄糊涂了

How to Alter a table for Identity Specification is identity SQL Server

MS SQL Server 2008 R2 IDENTITY 列的 JPA 注释