简体   繁体   English

在SQL Server的一个查询中使用外键同时将新数据插入到多个表中

[英]Insert New data into multiple tables with Foreign Key simultaneously in One query in sql server

I have two tables: 我有两个表:

tblDepartment : tblDepartment

Id    Name

and

tblEmployee : tblEmployee

Id    FullName    Dept_ID

Dept_ID is a foreign key for tblDepartment Dept_ID是一个外键tblDepartment

I want to insert a new record into both tables. 我想在两个表中插入一条新记录。

I tried this: 我尝试了这个:

declare @id int 

insert dbo.tblDepartment
   select Name='Name1'

select id = scope_Identity()

insert dbo.tblEmployee 
   select FullName = 'Name1' 

select Dept_Id=@id
select Id=@id

However, this is not working. 但是,这不起作用。 I searched through other posts, but they contain solutions for inserting existing data from one table into another, not creating a new record. 我搜索了其他帖子,但是它们包含用于将现有数据从一个表插入到另一个表而不创建新记录的解决方案。 How can I do this in one query? 如何在一个查询中做到这一点?

You need to use variables properly along with column lists for inserts. 您需要正确使用变量以及用于插入的列列表。 Assuming you are using SQL Server: 假设您正在使用SQL Server:

declare @id int ;

insert dbo.tblDepartment(Name)
    select 'Name1';
select @id = scope_Identity();

insert dbo.tblEmployee(FullName, Dept_Id)
    select 'Name1', @id;

Also, scope_identity() is okay for learning about such id's. 另外, scope_identity()也可以用于学习此类ID。 The safe way to really get this information is to use the output clause. 真正获得此信息的安全方法是使用output子句。

declare @id int 

insert dbo.tblDepartment(Name)
select 'Name1'
-- Don't insert any other statements before next line...
select @id=scope_Identity()


insert dbo.tblEmployee(Fullname, Dept_ID) 
select 'Name1',  @id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM