[英]Using the last inserted record's ID as a foreign key
I am making a database which links together two tables via the primary key of the first table. 我正在建立一个通过第一个表的主键将两个表链接在一起的数据库。 The one with the primary key which links the two is created first but how do i make the second record get the ID of the record I just created? 首先创建具有主键并将两者链接的键,但是如何使第二条记录获得我刚刚创建的记录的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');
I've had a look at the 'last()' function but not really sure how to utilise that. 我看过'last()'函数,但不确定如何使用它。 Other then that, I have no idea. 除此之外,我不知道。 Can someone help me out or guide me in the right direction. 有人可以帮助我或指导我正确的方向。
try this: 尝试这个:
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.