简体   繁体   English

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

[英]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.

相关问题 根据新插入记录的主键更新记录的外键字段 - Update record's foreign key field based on a newly inserted record's primary key 如何在与mvc中另一个表的外键有关系的html文本框中显示表的最后插入的ID(主键) - How to display the last inserted ID (primary key) of a table in a html textbox that is in a relationship with a foreign key of another table in mvc 实体框架,插入了引用最后一个Id的外键,同时也是同一张表上之前的集合 - Entity framework, Foreign Key referencing last Id was inserted, and also a collection of previous ones on the same table 使用PDO和PHP从MSSQL表中获取最后插入的记录的ID - Getting the id of the last inserted record from an MSSQL table using PDO and PHP 如何使用ASP.net获取SQL中最后插入记录的ID - How to get ID of the Last Inserted Record in SQL using ASP.net 如何对多个表使用最后插入的记录ID - how to use last inserted record id to multiple tables 使用SQL从表中为其关联的外键表中的每个关联记录选择一条记录 - Using SQL, select a single record from a table for each associated record in it's associated foreign key table 获取外键的最新实例 - Get last instances of foreign key's 获取最后插入的ID - Get the last inserted ID 读取最后插入的ID - Read Id of last inserted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM