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.
Only one identity column can be created per table.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With