Get List of all last inserted IDs to a table - sql

When I want to get last inserted ID to a table I use it like this:
insert into table1(col1,col2,col3)
values(val1,val2,val3)
declare #last_id int = scope_identity()
Now I have stored procedure that gets a value inserts multiple items:
insert into table1(col1,col2,col3)
select #val1,#val2,val3 from table2 where value=#value //#value is a single value that is passed to procedure as argument
now how can I get the list of IDs of these multiple rows that are added to table1?

declare #inserted table (Id int)
insert into table1(col1,col2,col3)
output inserted.Id into #inserted (Id)
select #val1,#val2,val3
from table2
where value=#value
select * from #inserted

The SCOPE_IDENTITY() gets you the last generated Identity Value in the identity column. to get all the newly inserted values you will need to make use of OUTPUT clause along with a table variable. See below how you can do that.
DECLARE #New_IDs TABLE(IDs INT)
insert into table1(col1,col2,col3)
OUTPUT inserted.Id_column INTO #New_IDs
select #val1,#val2,val3
from table2
where value=#value
SELECT * FROM #New_IDs

Related

Using sequence while inserting data into 2 tables at same time

I am trying to insert data using select statement. The table which I am inserting is having foreign key and it is sequence ID. How do I accomplish this? Because if I insert the sequence key in associated table first then how do I get the list of all the sequence ID to insert into the table.
Please note I am using insert with select statement so is there way to accomplish this without using cursor?
I think you can extract sequence value and then re-use it as many times as you want:
DECLARE #NextValue INT
SELECT #NextValue = NEXT VALUE FOR MySequence
SELECT NextValue = #NextValue
INSERT INTO PrimaryTable(PK_ID) VALUES (#NextValue);
INSERT INTO SecondaryTable(FK_ID) VALUES (#NextValue);
Here what I have tried.
DECLARE #MyTabVaR TABLE
(
FOREIGNKEY_ID INT,
COMMON_COL INT
);
INSERT INTO #MyTabVaR
SELECT NEXT VALUE FOR DBO.MY_SEQ,COMMON_COL FROM another_table2
INSERT INTO actual_table
SELECT FOREIGNKEY_ID FROM #MyTabVaR
INSERT INTO another_table
SELECT * FROM copy_table C
LEFT JOIN actual_table A
ON C.COMMON_COL=A.COMMON_COL
WHERE A.FOREIGNKEY_ID IS NOT NULL

Inserting into a Table the result between a variable and a table parameter

Having the following procedure:
CREATE PROCEDURE [dbo].[Gest_Doc_SampleProc]
#Nome nvarchar(255),
#Descritivo nvarchar(255),
#SampleTable AS dbo.IDList READONLY
AS
DECLARE #foo int;
SELECT #foo=a.bar FROM TableA a WHERE a.Nome=#Nome
IF NOT EXISTS (SELECT a.bar FROM TableA a WHERE a.Nome=#Nome)
BEGIN
INSERT INTO TableA VALUES (#Nome,#Descritivo)
INSERT INTO TableB VALUES (scope_identity(),#SampleTable)
END
I am trying, as shown, inserting into TableB all the values of SampleTable, together with the scope_identity.
SampleTable is as:
CREATE TYPE dbo.SampleTable
AS TABLE
(
ID INT
);
GO
How can I correctly achieve this?
The right way to do this type of work is the OUTPUT clause. Although technically not needed for a single row insert, you might as well learn how to do it correctly. And even what looks like a single row insert can have an insert trigger that does unexpected things.
PROCEDURE [dbo].[Gest_Doc_SampleProc] (
#Nome nvarchar(255),
#Descritivo nvarchar(255),
#SampleTable AS dbo.IDList
) READONLY AS
BEGIN
DECLARE #ids TABLE (id int);
DECLARE #foo int;
SELECT #foo = a.bar
FROM TableA a
WHERE a.Nome = #Nome;
IF NOT EXISTS (SELECT 1 FROM TableA a WHERE a.Nome = #Nome)
BEGIN
INSERT INTO TableA (Nome, Descritive)
OUTPUT Inserted.id -- or whatever the id is called
INTO #ids;
VALUES (#Nome,#Descritivo)
INSERT INTO TableB (id, sampletable)
SELECT id, #SampleTable
FROM #ids;
END;
END; -- Gest_Doc_SampleProc
In addition to using OUTPUT, this code also adds column lists to the INSERTs. That is another best practice.

How to Lock multiple tables for Insert command in Sql

This is my table Structure
When I insert Data into the first table, it will have multiple entries in table 2
I am Using code
To Get ID
Select MAX(ID)+1 From Table1
To Insert Data
Insert Into Table1 Values('1','abc','add1');
Insert into table2 values('1','med','english');
Insert into table2 values('1','eng','english');
Code is working fine for single computer but when we used in application in multiple terminals it is inserting wrong data i.e. data of another id in table2
You need ensure that the ID column of table1 is an identity column and then do the following:
DECLARE #ID INT
INSERT table1 ([columns])
VALUES (...)
SELECT #ID = SCOPE_IDENTITY()
INSERT table2 (table1ID, [columns])
VALUES (#ID, ...)
You can read more about SCOPE_IDENTITY() here.
MAX(ID) will include ID values created by other processes, which is why your second insert is mixing up data.

INSERT ONLY SPECIFIC COLUMN FROM A STORED PROCEDURE RESULT

I want to know if it is possible to insert to a table from a specific column of result from a stored procedure?
Something like:
declare #temp as table(
id int
)
insert #temp
exec getlistofStudents --returns multiple columns
this is an example only, Thanks for the help..
You can take a 2 step approach. First INSERT INTO a #TempTable, then populate the #TempVariable with another INSERT INTO, selecting the single column.
DECLARE #temp AS TABLE
(
ID int
);
CREATE TABLE #tempTable1
(
Column1 int,
Column2 int
);
INSERT INTO #tempTable1
Exec getlistofStudents
INSERT INTO #temp
SELECT Column1 FROM #tempTable1

Help with T-SQL script: Insert record, then use identity of that insert on another statement?

Just as a preface, I'm not very knowledgeable on T-SQL syntax.
I'd like to create a simple SQL script that will make 3 insert statements.
Insert A
Insert B
Insert C
Insert A statement's identity or "ID" would be needed in insert B statement.
And both the identities Inserts A & B would be needed in Insert C statement.
Pseudo code would look something like:
INSERT INTO tableA
VALUES ('blah', 'blah')
INSERT INTO tableB
VALUES (IDENTITY_FROM_A_INSERT, 'foo')
INSERT INTO tableC
VALUES (IDENTITY_FROM_A_INSERT, IDENTITY_FROM_B_INSERT)
How would I go about writing this script?
Use SCOPE_IDENTITY() after each insert in order to get the identity of the inserted row (in the current session).
I have used two variables to capture the two identities and then insert them into the third table:
DECLARE #Id1 INT
DECLARE #Id2 INT
INSERT INTO tableA VALUES ('blah', 'blah')
SET #Id1 = SELECT SCOPE_IDENTITY()
INSERT INTO tableB VALUES (IDENTITY_FROM_A_INSERT, 'foo')
SET #Id2 = SELECT SCOPE_IDENTITY()
INSERT INTO tableC VALUES (#Id1, #Id2)
scope_identity() is perfect for integer identifiers on single-record insertions (+1 to the other answer btw). However, if you find yourself using a guid/uniqueidentifier (newsequentialid(), newid(), etc) or inserting multiple records at once, you'll need something a little different:
declare #id uniqueidentifier;
-- Table variable for storing your newly inserted identifiers:
declare #NewlyInsertedIds table
(
[Id] uniqueidentifier
);
insert [MyTable]
(
[Blah1]
,[Blah2]
)
-- in the output clause you can access the inserted/deleted pseudo tables:
ouptut inserted.[Id]
into #NewlyInsertedIDs
(
[Id]
)
values
(
'Blah'
,'Blah'
);
select
#id = [Id]
from #NewlyInsertedIds;
Check out the OUTPUT Clause for more information.