我试图从一个select语句插入多个表。有可能吗?
以下是我在这里要做的事情:
(Array -> Parser a)
答案 0 :(得分:7)
您可以使用OUTPUT
子句插入第二个表。如果要插入两个以上的表,则必须使用其他方法。
示例数据
DECLARE @MainTable TABLE (Name nvarchar(50), Address nvarchar(50));
DECLARE @T1 TABLE (Name nvarchar(50), Address nvarchar(50));
DECLARE @T2 TABLE (Name nvarchar(50), Address nvarchar(50));
INSERT INTO @MainTable (Name, Address) VALUES
('Name1', 'Address1'),
('Name2', 'Address2'),
('Name3', 'Address3');
<强>查询强>
INSERT INTO @T1 (Name, Address)
OUTPUT inserted.Name, inserted.Address INTO @T2 (Name, Address)
SELECT Name, Address
FROM @MainTable
;
<强>结果强>
SELECT * FROM @T1;
SELECT * FROM @T2;
+-------+----------+
| Name | Address |
+-------+----------+
| Name1 | Address1 |
| Name2 | Address2 |
| Name3 | Address3 |
+-------+----------+
+-------+----------+
| Name | Address |
+-------+----------+
| Name1 | Address1 |
| Name2 | Address2 |
| Name3 | Address3 |
+-------+----------+
执行计划
答案 1 :(得分:-1)
INSERT INTO school_year_studentid
(student_id,syrid)
VALUES (
(
SELECT student_id
FROM student
), (
SELECT syr_id
FROM school_year
)
)