Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use generated identity for another column within the same insert only sometimes

Tags:

sql

sql-server

All similar questions are suggesting solutions for full copy of one column to another but that isn't my requirement.

Basically I'm adding say employees and while adding I have the option to make them a teamlead(of a new team). There is a teamlead id column which stores the employee id of the teamlead for each employee.

So while adding an employee who is going to be a teamlead, his teamlead column should hold his just generated employee id.

Is it possible to do that in a single insert? Someone said the value generation is done after the execution of the insert. I'm not sure how to proceed.

Edit: I don't have a working for a single insert. Right now I'm inserting and updating like this:

declare @TLID int
CREATE TABLE employees (
    Id int NOT NULL IDENTITY (1, 1),
    Name varchar(255),
    TeamLeadID int
);

if(@isTeamLead=1) --stored procedure parameter
begin
insert into employees(name)
values('Mark')
select @TLID=SCOPE_IDENTITY()
update employees set TeamLeadID=@TLID where id=@TLID
end
else 
begin
insert into employees(name,TeamLeadID)
values('Mark',16)
end

Wondering if a single insert can work for the first case.

like image 567
Arin Avatar asked Jun 22 '18 07:06

Arin


People also ask

Can we have 2 identity columns in a table?

Only one identity column can be created per table.

Is an identity column defined as generated always?

Identity columns are defined with the GENERATED ALWAYS or GENERATED BY DEFAULT clause. GENERATED ALWAYS means that Db2 generates a value for the column, and you cannot insert data into that column.

How do I add an identity column to an existing column?

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.


1 Answers

No you can't do this with a single insert.

You would need an insert then an update back to the same row to set the other column value back to the just inserted IDENTITY column value.

But there are some other approaches you can use.

You could use a sequence rather than an identity. Then you will know the value before insert and can simply use it in both columns.

Or you could just have NULL for the teamleadid column for employees that are team leads. And potentially use ISNULL(teamleadid, id) to calculate the result either as a computed column or at SELECT time.

like image 73
Martin Smith Avatar answered Oct 26 '22 22:10

Martin Smith