Link to home
Start Free TrialLog in
Avatar of mmedi005
mmedi005

asked on

How can i create a record and find its id to create more records in other tables all at the same time?

I have 2 tables.

employee
employee_cell

When i insert an employee a employeeid is created, how can i get that key and insert something into employee_cell all at the same time?




Avatar of Aneesh
Aneesh
Flag of Canada image


you have to enable the identity property for EmployeeID  after the first insert, the last inserted EmployeeID can be retrieved using SCOPE_IDENTITY()

DECLARE @LastEmpID int
INSERT INTO Employee
SELECT ....
SELECT @LastEmpID = scope_identity()
INSERT INTO Employee_Cell (EmployeeID, ... )
select @LastEmpID, ....
Oops.. I guess SCOPE_IDENTITY would do a better job since it works within the same scope  :-)
Avatar of mmedi005
mmedi005

ASKER

>>you have to enable the identity property for EmployeeID  after the first insert, the last inserted EmployeeID can be retrieved using SCOPE_IDENTITY()

DECLARE @LastEmpID int
INSERT INTO Employee
SELECT ....
SELECT @LastEmpID = scope_identity()
INSERT INTO Employee_Cell (EmployeeID, ... )
select @LastEmpID, ....

so will this work?

INSERT INTO employee(john,doe)VALUES(first,last)
@lastID = scope_identity()
INSERT INTO employee_cell(@lastID,555-5555)
ASKER CERTIFIED SOLUTION
Avatar of Aneesh
Aneesh
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
makes sense....

why this in the second insert?
INSERT INTO employee_cell
SELECT @lastID,'555-5555'
this is what i have set for employeeid

Identity Specification    Yes
      (Is Identity)             Yes
      Identity Increment   1
      Identity Seed          1


are these settings correct to use scope_identity()?
Yes, it means it will start the seeding at 1 and increment by 1 for each row entered.