将tbl1的主键插入到tbl2的外键中,将tbl1,tbl2的主键插入到tbl3的外键中

时间:2015-10-02 21:36:02

标签: sql-server

 CREATE TABLE tbl1 as [departments]
 (
   deptId int identity primary key,
   deptName nvarchar(40)
 )

 CREATE TABLE tbl2 as [teachers]
 (
   teacherId int identity primary key,
   teacherName nvarchar(40),
   deptId int references departments
 )

CREATE TABLE tbl3 as [departmentChiefs]
(
  deptId int references departments,
  teacherId int references teachers,
  chiefDate date
)

我想将(departments)表的主键插入(教师)表的外键中,同时将(部门和教师)的主键插入部门外键中

1 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @DeptId INT, @TeacherId INT;

INSERT INTO departments (deptName) VALUES ('My Department');
SELECT @DeptId = SCOPE_IDENTITY();

INSERT INTO teachers (teacherName, deptId) VALUES ('Joe Smith', @DeptId);
SELECT @TeacherId = SCOPE_IDENTITY();

INSERT INTO departmentChiefs (deptId, teacherId, chiefDate) VALUES (@DeptId, @TeacherId, GETDATE());

SCOPE_IDENTITY返回当前作用域中插入的最新标识值,结果可用作另一个INSERT语句的输入。您可能还希望在使用之前进行一些错误检查(例如,确保它不是NULL。)