This question already has answers here:
Return the id of the just added row
(5 answers)
Closed 8 years ago.
I am using SQL Server Management Studio. I have table named faculty and its attribute are id, Name and dean. I want to get last inserted record id in this table.
eg:
id Name dean
1 abc xyz
2 efg sss
3 ert yui
I just want to get 3rd id only, not 3rd row.
Just last inserted id that is 3 in this case.
You can use the SCOPE_IDENTITY() in your stored procedure to get last inserted record id.
SELECT SCOPE_IDENTITY() :- It will returns the last identity value inserted into an
identity column in the same scope.
SELECT ##IDENTITY :- ##IDENTITY will return the last identity value entered
into a table in your current session.
SELECT IDENT_CURRENT(‘tablename’) :- IDENT_CURRENT is not limited by scope and
session; it is limited to a specified table.
There are other options also such as
1. Select Top 1 id From Table Order by id desc
2. SELECT max(id) FROM table
Refer msdn http://msdn.microsoft.com/en-us/library/ms190315.aspx
and
http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
You can Use
##IDENTITY, SCOPE_IDENTITY, IDENT_CURRENT
see this Link ##IDENTITY, SCOPE_IDENTITY, IDENT_CURRENT
Related
This question already has answers here:
Sql Server return the value of identity column after insert statement
(7 answers)
How to get the identity of an inserted row?
(15 answers)
Closed 28 days ago.
I have a result set like below, RefId column will be empty initially. I need to loop through this result set insert values into one table ex : TableA , get the inserted row's identity (primary key) column value of the inserted rows and do some more manipulations.
I tried with cursors, since they are not recommended to use, how else can I do this in tsql ?
Result set query :
Insert into TableA(column1,column2,column3)
select column1, column2, column3 from Table B -- I want the identity values of the rows inserted into TableA,
I need them in another result set/ temp table or table variable along with the source values (TableB's select list values)
This is my table.
Ticket(id int auto_increment,name varchar(50));
after inserting into this table i want send id and name to mail..
how can i get the last Inserted value.
help to solve this...
Look into: Scope_identity
SCOPE_IDENTITY()
The table which is having Identity Property from that table we can get the last inserted record id will be like this
SELECT SCOPE_IDENTITY()
OR
But this is not a safe technique:
SELECT MAX(Id) FROM Ticket
OR
This is also not a safe technique:
SELECT TOP 1 Id FROM Ticket ORDER BY Id DESC
You should use SCOPE_IDENTITY() to get last primary key inserted value on your table. I guess it should be the ID value. Once you have it, do a SELECT using this ID and there you have it.
There is also ##IDENTITY but there are some differences using one or the another that could lead to inaccuracies on the values.
Check these detailed articles for more insights, a detailed description on how to use them, why they are different and some demo code:
For the last time, NO, you can't trust IDENT_CURRENT()
sql server identity vs scope_identity vs ident_current retrieve last inserted identity of record
For SQL Server before 2008 R2 Service Pack 1 (Link):
You may receive incorrect values when using SCOPE_IDENTITY() and
##IDENTITY
In that case, the OUTPUT clause is the safest mechanism:
DECLARE #InsertedRows AS TABLE (Id int)
DECLARE #NewId AS INT
INSERT INTO HumanResources.Employees
( /* column names */)
OUTPUT Inserted.Id INTO #InsertedRows
VALUES (/* column values */)
SELECT #NewId = Id FROM #InsertedRows
add auto increement Field in your table like.... index (INT,AUTO INCREEMENT)
then before insert or any operation done c get your last record by getting max(index)
This question already has answers here:
How to get last inserted id?
(16 answers)
Closed 10 years ago.
I want to get the new created ID when you insert a new record in table.
I read this: http://msdn.microsoft.com/en-us/library/ms177564.aspx but it needs to create temporary table.
I want to return the ID after executing INSERT statement (assuming executing just one INSERT).
Example:
1 Joe Joe
2 Michael Mike
3 Zoe Zoe
When executing an INSERT statement, I want to return the created ID, means 4.
Can tell me how to do that using SQL statement or it is not possible ?
If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.
There are at least two more options - ##IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
Assuming a simple table:
CREATE TABLE dbo.foo(ID INT IDENTITY(1,1), name SYSNAME);
We can capture IDENTITY values in a table variable for further consumption.
DECLARE #IDs TABLE(ID INT);
-- minor change to INSERT statement; add an OUTPUT clause:
INSERT dbo.foo(name)
OUTPUT inserted.ID INTO #IDs(ID)
SELECT N'Fred'
UNION ALL
SELECT N'Bob';
SELECT ID FROM #IDs;
The nice thing about this method is (a) it handles multi-row inserts (SCOPE_IDENTITY() only returns the last value) and (b) it avoids this parallelism bug, which can lead to wrong results, but so far is only fixed in SQL Server 2008 R2 SP1 CU5.
You can use:
SELECT IDENT_CURRENT('tablename')
to access the latest identity for a perticular table.
e.g. Considering following code:
INSERT INTO dbo.MyTable(columns....) VALUES(..........)
INSERT INTO dbo.YourTable(columns....) VALUES(..........)
SELECT IDENT_CURRENT('MyTable')
SELECT IDENT_CURRENT('YourTable')
This would yield to correct value for corresponding tables.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get the primary key of the last row inserted into the table
In SQL Server 2008, I have a stored proc that inserts in a table which includes identity column for ID. I need to return the ID of record to my application so that I can use it for related tables.
How can I get generated ID by SQL?
Use select Scope_Identity() to get the ID
A separate SQL statement
SELECT SCOPE_IDENTITY()
Or the OUTPUT clause
INSERT MyTable (...=
OUTPUT INSERTED.KeyCol
VALUES (...) --Or SELECT ... FROM Another table)
There are multiple options that are a bit different:
SCOPE_IDENTITY() - that's what I would use
IDENT_CURRENT( 'table_name' )
##IDENTITY
How do I retrieve the ID of an inserted row in SQL?
Users Table:
Column | Type
--------|--------------------------------
ID | * Auto-incrementing primary key
Name |
Age |
Query Sample:
insert into users (Name, Age) values ('charuka',12)
In MySQL:
SELECT LAST_INSERT_ID();
In SQL Server:
SELECT SCOPE_IDENTITY();
In Oracle:
SELECT SEQNAME.CURRVAL FROM DUAL;
In PostgreSQL:
SELECT lastval();
(edited: lastval is any, currval requires a named sequence)
Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.
In SQL Server, you can do (in addition to the other solutions already present):
INSERT INTO dbo.Users(Name, Age)
OUTPUT INSERTED.ID AS 'New User ID'
VALUES('charuka', 12)
The OUTPUT clause is very handy when doing inserts, updates, deletes, and you can return any of the columns - not just the auto-incremented ID column.
Read more about the OUTPUT clause in the SQL Server Books Online.
In Oracle and PostgreSQL you can do this:
INSERT INTO some_table (name, age)
VALUES
('charuka', 12)
RETURNING ID
When doing this through JDBC you can also do that in a cross-DBMS manner (without the need for RETURNING) by calling getGeneratedKeys() after running the INSERT
I had the same need and found this answer ..
This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
#comp_name varchar(55) = 'Big Company',
#comp_regno nchar(8) = '12345678',
#comp_email nvarchar(50) = 'no1#home.com',
#recID INT OUTPUT
-- The '#recID' is used to hold the Company auto generated ID number that we are about to grab
AS
Begin
SET NOCOUNT ON
DECLARE #tableVar TABLE (tempID INT)
-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '#recID'.
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO #tableVar
-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.
VALUES (#comp_name, #comp_regno, #comp_email)
SET #recID = (SELECT tempID FROM #tableVar)
-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '#recID'. '#recID' now has the ID number you want and you can use it how you want like i have used it below.
INSERT INTO staff(Staff_comp_id)
VALUES (#recID)
End
-- So there you go. I was looking for something like this for ages, with this detailed break down, I hope this helps.