Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the autoincremnt value after inserting record using SQL Server

I'm developing a project using VB.NET connected to SQL Server database

and in this project i need to get the value of column called "ID" after inserting a record to the database immediately.

thanx.

like image 281
Abdulrhman Avatar asked Dec 08 '09 06:12

Abdulrhman


People also ask

How can I get Auto_increment value after insert in SQL Server?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

How can I get auto increment value after insert?

To know the current auto_increment value, we can use the last_insert_id() function. Firstly, we will create a table with the help of INSERT command. Now, we will see how many records have I inserted into my table with the help of SELECT command. Therefore, the last auto increment is 4.

How can I return ID after insert in SQL Server?

We use SCOPE_IDENTITY() function to return the last IDENTITY value in a table under the current scope. A scope can be a module, trigger, function or a stored procedure. We can consider SQL SCOPE_IDENTITY() function similar to the @@IDENTITY function, but it is limited to a specific scope.

Where is auto increment in SQL?

The auto increment in SQL is a feature that is applied to a field so that it can automatically generate and provide a unique value to every record that you enter into an SQL table. This field is often used as the PRIMARY KEY column, where you need to provide a unique value for every record you add.


2 Answers

CREATE TABLE dbo.SomeTable (
     ID int IDENTITY
    ,[NAME] varchar(50)
    );
go

INSERT INTO dbo.SomeTable ([Name])
SELECT 'Joe' UNION
SELECT 'Jim' UNION
SELECT 'JIll'
;

SELECT  ident_current('dbo.SomeTable') AS [LastID_1]
        ,@@IDENTITY AS [LastID_2]
        ,scope_identity() AS [LastID_3]
;   

USES:

  • ident_current ('TableName') for a specific table, not limited by scope and session
  • @@IDENTITY last ID in current session
  • scope_identity() last ID in current session, current scope
like image 186
Damir Sudarevic Avatar answered Oct 23 '22 02:10

Damir Sudarevic


Have a look at SCOPE_IDENTITY (Transact-SQL)

like image 5
Adriaan Stander Avatar answered Oct 23 '22 02:10

Adriaan Stander