/* 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;