Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server return the value of identity column after insert statement

Is it possible in sql server using stored procedure to return the identity column value in a table against which some values are inserted? For example using stored procedure if we insert data in a table:

Table TBL

  • UserID integer, identity, auto-incremented
  • Name varchar
  • UserName varchar
  • Password varchar

So if I run the store procedure inserting some values like:

 Insert into TBL (Name, UserName, Password)  Values ('example', 'example', '$2a$12$00WFrz3dOfLaIgpTYRJ9CeuB6VicjLGhLset8WtFrzvtpRekcP1lq') 

How can I return the value of UserID at which this insertion will take place. I need The value of UserID for some other operations, can anybody solve this?

like image 444
user2599269 Avatar asked Aug 01 '13 12:08

user2599269


People also ask

How do I get the identity column value after insert?

Once we insert a row in a table, the @@IDENTITY function column gives the IDENTITY value generated by the statement. If we run any query that did not generate IDENTITY values, we get NULL value in the output. The SQL @@IDENTITY runs under the scope of the current session.

How do I get the last inserted identity column value in SQL?

SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use. IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope.

How can get current value of identity column in SQL Server?

The current identity value is larger than the maximum value in the table. Execute DBCC CHECKIDENT (table_name, NORESEED) to determine the current maximum value in the column. Next, specify that value as the new_reseed_value in a DBCC CHECKIDENT (table_name, RESEED,new_reseed_value) command.


2 Answers

Insert into TBL (Name, UserName, Password) Output Inserted.IdentityColumnName  Values ('example', 'example', 'example') 
like image 130
Amit Singh Avatar answered Sep 23 '22 00:09

Amit Singh


send an output parameter like

@newId int output 

at the end use

    select @newId = Scope_Identity()        return @newId  
like image 31
Md. Parvez Alam Avatar answered Sep 21 '22 00:09

Md. Parvez Alam