Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store the value of output inserted._ID to local variable to reuse it in another query

I want to simply execute a SQL query that would return the current id of the row that was added to a table, example:

insert into V_Post output inserted._ID values('Please return the id of THIS row :)')

That shall returns a number like 155

So the aim of my question is to store that number in some kind of local variable like XVALUE and then use this XVALUE in any other SQL query like:

insert into V_Posts values(1, XVALUE, null, GETDATE(), null, null, 1)

So i thougt of something like:

int XVALUE = insert into V_Post output inserted._ID values('Please return the id of THIS row :)')

insert into V_Posts values(1, XVALUE, null, GETDATE(), null, null, 1)

OR

insert into V_Posts values(1, insert into V_Post output inserted._ID values('Please return the id of THIS row :)'), null, GETDATE(), null, null, 1)

But both it didn't work :(

I hope i explained my question well and i really thank you in advance for your help.

EDIT

Please notice i have two tables: V_posts and V_post

like image 424
BOSS Avatar asked Nov 17 '13 18:11

BOSS


1 Answers

IDENTITY COLUMN

If it is an identity column and you are only inserting a single row then you can use SCOPE_IDENTITY() function to get the last generated Identity value within the scope of the current session.

DECLARE @NewValue INT;
insert into V_Post 
values('Please return the id of THIS row :)')
SET @NewValue = SCOPE_IDENTITY()

IF NOT IDENTITY Column Or Multiple Identity values

If it is an identity column and you are inserting multiple rows and want to return all the newly inserted Identity values, or it is not an identity column but you need the last inserted value then you can make sure of OUTPUT command to get the newly inserted values.

DECLARE @tbl TABLE (Col1 DataType)
DECLARE @NewValue Datatype;

insert into V_Post 
output inserted._ID INTO @tbl
values('Please return the id of THIS row :)')

SELECT @NewValue = Col1 FROM @tbl
like image 126
M.Ali Avatar answered Oct 16 '22 17:10

M.Ali