SQL Server : multiple queries with Auto ID identity - sql-server

I have a stored procedure that inserts some values to a specific table:
CREATE PROCEDURE AccessoiresAddOrder
#AccessoireID int,
#Qte int,
#ClientID int,
#Price Varchar(50),
#Totalprice Varchar(50),
#Date DateTime,
#ValueInt
AS
INSERT INTO [dbo].[Accessoires_Orders] ([AccessoireID], [Qte], [ClientID], [Price], [Totalprice],[Date])
VALUES (#AccessoireID, #Qte, #ClientID, #Price, #Totalprice, #Date)
INSERT INTO [dbo].[Accessoires_ordervalue] (Value)
VALUES (#Value)
The Acccessoires_Orders table has a column ID which is "auto identity". Is there any way to get that value during the procedure execution?
int ID = Max(Accessoires_Orders.ID) + 1
Why ?
Because this procedure can be executed by multiple users at the same exact time.

You can use either:
SELECT #MyNewID = SCOPE_IDENTITY()
SELECT #MyNewID = ##IDENTITY
SCOPE_IDENTITY() will always give you the value created by the query itself. ##IDENTITY can give you that value as well, but if a trigger executes after your insert, it will return the ID generated by the trigger instead.
Since you want the ID you created in the query, you'd be best off using SCOPE_IDENTITY().

You can use ##IDENTITY variable that returns you the last identity value returned within the current session - see: MSDN ##IDENTITY. However, if there are e.g. some triggers behind the table you can receive an identity value created by this trigger in a completely different table...
So generally recommended way is to rather use the SCOPE_IDENTITY() - see: MSDN SCOPE_IDENTITY()

After inserting a record to a able with an Identity column, the latest value inserted in the last row will be available in ##Identity variable.
You can select value of ##Identity and return is from your stored procedure. Following is a sample code for that.
INSERT INTO Production.Location (Name, CostRate, Availability, ModifiedDate)
VALUES ('Damaged Goods', 5, 2.5, GETDATE());
GO
SELECT ##IDENTITY AS 'Identity';
GO

Related

Using ##identity or output when inserting into SQL Server view?

(forgive me - I'm new to both StackOverflow & SQL)
Tl;dr - When using ##identity (or any other option such as scope_identity or output variable), is it possible to also use a view? Here is an example of a stored procedure using ##identity:
--SNIP--
DECLARE #AID INT
DECLARE #BID INT
INSERT INTO dbo.A (oct1)
VALUES
(#oct1)
SELECT #AID = ##IDENTITY;
INSERT INTO dbo.B (duo1)
VALUES
(#duo2)
SELECT #BID = ##IDENTITY
INSERT INTO dbo.tblAB (AID, BID)
VALUES
(#AID, #BID)
GO
Longer:
When inserting into a table, you can capture the current value of the identity seed using ##identity. This is useful if you want to insert into table A and B, capture the identity value, then insert into table AB relating A to B. Obviously this is for purposes of data normalization.
Let's say you were to abstract the DB Schema with a few that performs inner joins on your tables to make the data easier to work with. How would you populate the cross reference tables properly in that case? Can it be done the same way, if so, how?
Avoid using ##IDENTITY or SCOPE_IDENTITY() if your system is using Parallel plans as there is a nasty bug. Please refer -
http://connect.microsoft.com/SQL/feedback/ViewFeedback.aspx?FeedbackID=328811
Better way to fetch the inserted Identity ID would be to use OUTPUT clause.
CREATE TABLE tblTest
(
Sno INT IDENTITY(1,1) NOT NULL,
FirstName VARCHAR(20)
)
DECLARE #pk TABLE (ID INT)
INSERT INTO tblTest(FirstName)
OUTPUT INSERTED.Sno INTO #pk
SELECT 'sample'
SELECT * FROM #pk
EDIT:
It would work with Views as well. Please see the sample below. Hope this is what you were looking for.
CREATE VIEW v1
AS
SELECT sno, firstname FROM tbltest
GO
DECLARE #pk TABLE (ID INT)
INSERT INTO v1(FirstName)
OUTPUT INSERTED.Sno INTO #pk
SELECT 'sample'
SELECT ID FROM #pk
##IDENTITY returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
SCOPE_IDENTITY() returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like ##IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well
Although the issue with either of these is fixed by microsoft , I would suggest you should go with "OUTPUT", and yes, it can be used with view as well

How can SCOPE_IDENTITY return null when ##IDENTITY does not?

After executing an insert, I either select SCOPE_IDENTITY or ##IDENTITY.
SCOPE_IDENTITY returns null but ##IDENTITY does not.
I don't understand how this is possible.
Can you think of a reason why this happens?
here is one example of how SCOPE_IDENTITY() will be null but ##IDENTITY will have a value:
insert into a table with no identity,
that table has an insert trigger that
then inserts into a history table with
an identity. SCOPE_IDENTITY() will be
null (no identity in the local scope),
but ##IDENTITY will report the
identity from the trigger.
FYI, there is a known bug with SCOPE_IDENTITY(): https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=328811
Your best bet with identities is to use OUTPUT INTO, it can capture a set of IDs and is not subject to the SCOPE_IDENTITY() bug:
declare #x table (tableID int identity not null primary key, datavalue varchar(10))
declare #y table (tableID int, datavalue varchar(10))
INSERT INTO #x values ('aaaa')
INSERT INTO #x values ('bbbb')
INSERT INTO #x values ('cccc')
INSERT INTO #x values ('dddd')
INSERT INTO #x values ('eeee')
INSERT INTO #x
(datavalue)
OUTPUT INSERTED.tableID, INSERTED.datavalue --<<<<OUTPUT INTO SYNTAX
INTO #y --<<<<OUTPUT INTO SYNTAX
SELECT
'value='+CONVERT(varchar(5),dt.NewValue)
FROM (SELECT id as NewValue from sysobjects where id<20) dt
ORDER BY dt.NewValue
select * from #x
select * from #y
KM hit the nail on the head:
##IDENTITY gives you the last IDENTITY value inserted - no matter where in which table it was inserted (think triggers, e.g. into audit tables! Or even a cascade of triggers.....)
SCOPE_IDENTITY() gives you the last IDENTITY inserted in the scope of your statement, e.g. on the table(s) that your own, actual statement referenced (not those that might have been touched by a trigger)
SCOPE_IDENTITY will also return NULL when the insert is by sp_executesql as you are no longer in the scope of the INSERT!
I found this on MSDN:
The SCOPE_IDENTITY() function will return the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.
You can read here: http://msdn.microsoft.com/en-us/library/ms190315.aspx
Your SQL code would be very helpful.

How Do You Tell What Next Identity Column Will Be?

Is there a tsql query to tell what SQL server identity column value it expects to use for the next row insert?
Edited to add:
I deleted and recreated a table with
[personID] [int] IDENTITY(1,1) NOT NULL
as part of my CREATE TABLE command. I've also attempted to reseed identity columns while removing all information in that table and that hasn't always worked. It got me to wondering if there was a way to see what SQL expected to use for your next identity column number.
You probably want to use SCOPE_IDENTITY not ##IDENTITY to restrict it to the identity value in the current scope. This avoids getting new identity values inserted by triggers into other tables and not the table you just inserted into.
But you can calculate what the next identity value is
SELECT IDENT_CURRENT('mytable') + IDENT_INCR('mytable') FROM mytable
The problem is you aren't guaranteed that is the value.
You'd have to have a lock such that other inserts are denied on the table when running it to ensure the value is accurate. Also after you run out of 32 bit integers I don't know what the logic is. I don't know whether it rolls over or fails.
Edit:
I just tested this (see below for SQL) and it doesn't return the correct value when there is no data.
And reseeding with DBCC CHECKIDENT ('tablename', RESEED, 200) actually resulted in the next value being 201 not 200.
CREATE TABLE willtest (myid integer IDENTITY(1,1), myvalue varchar(255))
SELECT IDENT_CURRENT('willtest') + IDENT_INCR('willtest')
INSERT INTO willtest (myvalue)
VALUES ('1')
INSERT INTO willtest (myvalue)
VALUES ('2')
INSERT INTO willtest (myvalue)
VALUES ('3')
INSERT INTO willtest (myvalue)
VALUES ('4')
INSERT INTO willtest (myvalue)
VALUES ('5')
INSERT INTO willtest (myvalue)
VALUES ('6')
INSERT INTO willtest (myvalue)
VALUES ('7')
INSERT INTO willtest (myvalue)
VALUES ('8')
SELECT IDENT_CURRENT('willtest') + IDENT_INCR('willtest')
DBCC CHECKIDENT ('willtest', RESEED, 200)
SELECT IDENT_CURRENT('willtest') + IDENT_INCR('willtest')
INSERT INTO willtest (myvalue)
VALUES ('200')
INSERT INTO willtest (myvalue)
VALUES ('201')
INSERT INTO willtest (myvalue)
VALUES ('202')
INSERT INTO willtest (myvalue)
VALUES ('203')
INSERT INTO willtest (myvalue)
VALUES ('204')
INSERT INTO willtest (myvalue)
VALUES ('205')
INSERT INTO willtest (myvalue)
VALUES ('206')
INSERT INTO willtest (myvalue)
VALUES ('207')
SELECT IDENT_CURRENT('willtest') + IDENT_INCR('willtest')
SELECT * FROM willtest
DROP TABLE willtest
No, there isn't any guaranteed way (although you can certainly find out what the next value might be, another command might go and use it before you can make any use of it). The only guaranteed value you can retrieve is the previously inserted identity value through SCOPE_IDENTITY() (which will return the identity value last generated for the current scope).
It's questionable what purpose why one would need to know the value before (when using an automatically incremented seeded identity column).
If you need to know the value before, then I recommend generating the ids yourself. You can do this with an ids table keyed on the table name, or, if you have scalability concerns (and you are using transactions) you can have an id table for each table that needs an id which would have the id to be inserted (and subsequently incremented).
Or, you could use a GUID, and you would be able to easily generate these on the client side before sending it to your database.
This piece of sql will give you the next identity column value (there are probably many reasons not to repeat this snippet in production code)
declare #nextid int;
declare #previousid int;
begin tran
insert into dbo.TestTable (Col1) values ('11');
select #nextid = SCOPE_IDENTITY();
rollback tran
select #previousid = #nextid -1
DBCC CHECKIDENT('dbo.TestTable', RESEED, #previousid);
select #nextid
this stackoverflow question gives some extra information - sql-identity-autonumber-is-incremented-even-with-a-transaction-rollback
SELECT IDENT_CURRENT('mytable') + IDENT_INCR('mytable') FROM mytable
Since you seed from 1 and increment by 1 (IDENTITY(1,1)), I'm wondering if you can create a procedure where you can set a variable like "Select ##IDENTITY + 1" or something like that.
Use GUID columns for your primary keys. Unless you have billions of records and thousands of requests per second, you probably won't notice the performance difference. But unless you like spending far too much time dealing with stupid issues like this, you will notice the difference in your stress level and life expectancy.

SQL: How to get the id of values I just INSERTed?

I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value.
Can you tell me how to do it the right way?
##IDENTITY is not scope safe and will get you back the id from another table if you have an insert trigger on the original table, always use SCOPE_IDENTITY()
This is how I do my store procedures for MSSQL with an autogenerated ID.
CREATE PROCEDURE [dbo].[InsertProducts]
#id INT = NULL OUT,
#name VARCHAR(150) = NULL,
#desc VARCHAR(250) = NULL
AS
INSERT INTO dbo.Products
(Name,
Description)
VALUES
(#name,
#desc)
SET #id = SCOPE_IDENTITY();
This works very nicely in SQL 2005:
DECLARE #inserted_ids TABLE ([id] INT);
INSERT INTO [dbo].[some_table] ([col1],[col2],[col3],[col4],[col5],[col6])
OUTPUT INSERTED.[id] INTO #inserted_ids
VALUES (#col1,#col2,#col3,#col4,#col5,#col6)
It has the benefit of returning all the IDs if your INSERT statement inserts multiple rows.
If your using PHP and MySQL you can use the mysql_insert_id() function which will tell you the ID of item you Just instered.
But without your Language and DBMS I'm just shooting in the dark here.
Again no language agnostic response, but in Java it goes like this:
Connection conn = Database.getCurrent().getConnection();
PreparedStatement ps = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
try {
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
rs.next();
long primaryKey = rs.getLong(1);
} finally {
ps.close();
}
If you are working with Oracle:
Inset into Table (Fields....) values (Values...) RETURNING (List of Fields...) INTO (variables...)
example:
INSERT INTO PERSON (NAME) VALUES ('JACK') RETURNING ID_PERSON INTO vIdPerson
or if you are calling from... Java with a CallableStatement (sry, it's my field)
INSERT INTO PERSON (NAME) VALUES ('JACK') RETURNING ID_PERSON INTO ?
and declaring an autput parameter for the statement
There's no standard way to do it (just as there is no standard way to create auto-incrementing IDs). Here are two ways to do it in PostgreSQL. Assume this is your table:
CREATE TABLE mytable (
id SERIAL PRIMARY KEY,
lastname VARCHAR NOT NULL,
firstname VARCHAR
);
You can do it in two statements as long as they're consecutive statements in the same connection (this will be safe in PHP with connection pooling because PHP doesn't give the connection back to the pool until your script is done):
INSERT INTO mytable (lastname, firstname) VALUES ('Washington', 'George');
SELECT lastval();
lastval() gives you the last auto-generated sequence value used in the current connection.
The other way is to use PostgreSQL's RETURNING clause on the INSERT statement:
INSERT INTO mytable (lastname) VALUES ('Cher') RETURNING id;
This form returns a result set just like a SELECT statement, and is also handy for returning any kind of calculated default value.
An important note is that using vendor SQL queries to retrieve the last inserted ID are safe to use without fearing about concurrent connections.
I always thought that you had to create a transaction in order to INSERT a line and then SELECT the last inserted ID in order to avoid retrieving an ID inserted by another client.
But these vendor specific queries always retrieve the last inserted ID for the current connection to the database. It means that the last inserted ID cannot be affected by other client insertions as long as they use their own database connection.
For SQL 2005:
Assuming the following table definition:
CREATE TABLE [dbo].[Test](
[ID] [int] IDENTITY(1,1) NOT NULL,
[somevalue] [nchar](10) NULL,
)
You can use the following:
INSERT INTO Test(somevalue)
OUTPUT INSERTED.ID
VALUES('asdfasdf')
Which will return the value of the ID column.
From the site i found out the following things:
SQL SERVER – ##IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record
March 25, 2007 by pinaldave
SELECT ##IDENTITY
It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.
##IDENTITY will return the last identity value entered into a table in your current session. While ##IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.
SCOPE_IDENTITY(), like ##IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
SELECT IDENT_CURRENT(‘tablename’)
It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
Remember that ##IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table. You should always use SCOPE_IDENTITY() to return the identity of the recently added row.
What database are you using? As far as I'm aware, there is no database agnostic method for doing this.
This is how I've done it using parameterized commands.
MSSQL
INSERT INTO MyTable (Field1, Field2) VALUES (#Value1, #Value2);
SELECT SCOPE_IDENTITY();
MySQL
INSERT INTO MyTable (Field1, Field2) VALUES (?Value1, ?Value2);
SELECT LAST_INSERT_ID();
sql = "INSERT INTO MyTable (Name) VALUES (#Name);" +
"SELECT CAST(scope_identity() AS int)";
SqlCommand cmd = new SqlCommand(sql, conn);
int newId = (int)cmd.ExecuteScalar();
Ms SQL Server: this is good solution even if you inserting more rows:
Declare #tblInsertedId table (Id int not null)
INSERT INTO Test ([Title], [Text])
OUTPUT inserted.Id INTO #tblInsertedId (Id)
SELECT [Title], [Text] FROM AnotherTable
select Id from #tblInsertedId
Rob's answer would be the most vendor-agnostic, but if you're using MySQL the safer and correct choise would be the built-in LAST_INSERT_ID() function.
SELECT ##Scope_Identity as Id
There is also ##identity, but if you have a trigger, it will return the results of something that happened during the trigger, where scope_identity respects your scope.
insert the row with a known guid.
fetch the autoId-field with this guid.
This should work with any kind of database.
An Environment Based Oracle Solution:
CREATE OR REPLACE PACKAGE LAST
AS
ID NUMBER;
FUNCTION IDENT RETURN NUMBER;
END;
/
CREATE OR REPLACE PACKAGE BODY LAST
AS
FUNCTION IDENT RETURN NUMBER IS
BEGIN
RETURN ID;
END;
END;
/
CREATE TABLE Test (
TestID INTEGER ,
Field1 int,
Field2 int
)
CREATE SEQUENCE Test_seq
/
CREATE OR REPLACE TRIGGER Test_itrig
BEFORE INSERT ON Test
FOR EACH ROW
DECLARE
seq_val number;
BEGIN
IF :new.TestID IS NULL THEN
SELECT Test_seq.nextval INTO seq_val FROM DUAL;
:new.TestID := seq_val;
Last.ID := seq_val;
END IF;
END;
/
To get next identity value:
SELECT LAST.IDENT FROM DUAL
In TransactSQL, you can use OUTPUT clause to achieve that.
INSERT INTO my_table(col1,col2,col3) OUTPUT INSERTED.id VALUES('col1Value','col2Value','col3Value')
FRI: http://msdn.microsoft.com/en-us/library/ms177564.aspx
Simplest answer:
command.ExecuteScalar()
by default returns the first column
Return Value
Type: System.Object
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
Copied from MSDN

In SQL Server is it possible to get "id" of a record when Insert is executed?

In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert?
duplicate of:
Best way to get identity of inserted row?
In .Net at least, you can send multiple queries to the server in one go. I do this in my app:
command.CommandText = "INSERT INTO [Employee] (Name) VALUES (#Name); SELECT SCOPE_IDENTITY()";
int id = (int)command.ExecuteScalar();
Works like a charm.
If you're inserting multiple rows, the use of the OUTPUT and INSERTED.columnname clause on the insert statement is a simple way of getting all the ids into a temp table.
DECLARE #MyTableVar table( ID int,
Name varchar(50),
ModifiedDate datetime);
INSERT MyTable
OUTPUT INSERTED.ID, INSERTED.Name, INSERTED.ModifiedDate INTO #MyTableVar
SELECT someName, GetDate() from SomeTable
Scope_identity() is the preferred way, see: 6 Different Ways To Get The Current Identity Value
SCOPE_IDENTITY(); is your best bet. And if you are using .NET just pass an our parameter and check the value after the procedure is run.
CREATE PROCEDURE [dbo].[InsertProducts]
#id INT = NULL OUT,
#name VARCHAR(150) = NULL,
#desc VARCHAR(250) = NULL
AS
INSERT INTO dbo.Products
(Name,
Description)
VALUES
(#name,
#desc)
SET #id = SCOPE_IDENTITY();
You have to select the scope_identity() function.
To do this from application code, I normally encapsulate this process in a stored procedure so it still looks like one query to my application.
I tend to prefer attaching a trigger to the table using enterprise manager. That way you don't need to worry about writing out extra sql statements in your code. Mine look something like this:
Create Trigger tblName
On dbo.tblName
For Insert
As
select new_id = ##IDENTITY
Then, from within your code, treat your insert statements like select statements- Just execute and evaluate the results. the "newID" column will contain the identity of the row you just created.
This is probably the best working solution I found for SQL Server..
Sql Server return the value of identity column after insert statement

Resources