e_taylor
e_taylor

Reputation: 1

How can I get ID from database while inserting some data, but I don't insert that ID that I need later

I am reading from a file and I have to insert it to database. I have tables like:

And I don't insert ID, it is added automatically in database (Guid). I want to insert data into the table ApplicationsForJobs which has columns (PersonId, JobId, SeasonId) and my question is: how can I get those IDs?

Upvotes: 0

Views: 1382

Answers (2)

Muhammad Imran Ansari
Muhammad Imran Ansari

Reputation: 43

In SQL DB, if table column is uniqueidentifier then you can get the result like:

DECLARE @IDs TABLE([ID] [uniqueidentifier]);
INSERT [Persons] ([name], [surname])
        OUTPUT INSERTED.[ID] INTO @IDs
VALUES (N'abc', N'xyz');

--Display the result set of the table variable.
SELECT [ID] FROM @IDs;

Same goes for Jobs and Season and then you will insert all these IDs into ApplicationsForJobs table.

If column is not uniqueidentifier then use the

Upvotes: 0

Ramin Faracov
Ramin Faracov

Reputation: 3303

The SQL Server DB has 2 ways for getting identity id field value during the insert process.

-- 1) when inserted many records 
insert into tbl_test (NAME, CODE)
OUTPUT inserted.id 
select NAME, CODE from tbl_test_data


-- 2) when inserted only one record 
insert into tbl_test (NAME, CODE)
VALUES ('Sarah', 'AB154342');
SELECT SCOPE_IDENTITY();

Upvotes: 1

Related Questions