使用最后插入的记录的ID作为外键

时间:2017-04-12 06:12:38

标签: sql-server tsql foreign-keys primary-key foreign-key-relationship

我正在创建一个数据库,它通过第一个表的主键将两个表链接在一起。首先创建链接两者的主键,但如何让第二条记录获取我刚刚创建的记录的ID?

create table Person
(

    Person_ID int IDENTITY(100000,1) primary key,
    First_Name varchar(20) not null,
    Last_Name varchar(20) not null,
)

create table Employee
(

    Employee_ID int identity(100000,1) primary key,
    Person_ID int references Person(Person_ID),
    Employee_Type varchar(10)
)

insert into Person(First_Name, Last_Name) values ('Michael', 'Chu');

insert into Employee(Person_ID, Employee_Type,) values (????????, 'Admin');

我已经看过了#last;()'功能但不确定如何利用它。除此之外,我不知道。有人可以帮助我或引导我朝着正确的方向前进。

1 个答案:

答案 0 :(得分:0)

试试这个:

create table Person
(

    Person_ID int IDENTITY(100000,1) primary key,
    First_Name varchar(20) not null,
    Last_Name varchar(20) not null,
)

create table Employee
(

    Employee_ID int identity(100000,1) primary key,
    Person_ID int references Person(Person_ID),
    Employee_Type varchar(10)
)

DECLARE @myID AS INT

insert into Person(First_Name, Last_Name) values ('Michael', 'Chu');

SET @myID = @@IDENTITY

insert into Employee(Person_ID, Employee_Type,) values (@myID , 'Admin');