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)表的主键插入(教师)表的外键中,同时将(部门和教师)的主键插入部门外键中
答案 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
。)