如何插入一个基于多行子查询的table?
How to insert into a table based on a multi-row subquery?
我有一个 Dashboard_Diagram
table:
CREATE TABLE Dashboard_Diagram
(
diagram_id TINYINT,
name VARCHAR(50)
)
INSERT INTO Dashboard_Diagram
SELECT 1, 'Radar'
UNION ALL
SELECT 2, 'Bar'
UNION ALL
SELECT 3, 'Pie'
我有 Dashboard_Configuration
table:
CREATE TABLE SomeTable
(
user_id UNIQUEIDENTIFIER,
diagram_id TINYINT
)
和@user_id
:
DECLARE @user_id UNIQUEIDENTIFIER = 'E4F77F2C-8AA1-493A-94A3-03EA212453D4'
我想根据 Dashboard_Diagram
中的行动态地将行插入 Dashboard_Configuration
。所以静态这看起来像:
INSERT INTO Dashboard_Configuration
@userId, 1
. . .
我试过了:
INSERT INTO Dashboard_Configuration
@user_id, (SELECT diagram_id FROM Dashboard_Diagram)
但这会引发错误,因为子查询 returns 有多个值:
Msg 512, Level 16, State 1, Line 7
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
如何根据来自另一个 table 的动态行数插入 table?
使用insert . . . select
:
INSERT INTO Dashboard_Configuration (User_id, name)
SELECT @user_id, name
FROM Dashboard_Diagram;
请注意,这也明确列出了列。名称可能不正确(您没有在问题中指定它们),但最好列出列。
编辑:
上面存在类型冲突。你真的打算这样做吗?
INSERT INTO Dashboard_Configuration (User_id, diagram_id)
SELECT @user_id, dd.diagram_id
FROM Dashboard_Diagram dd;
我有一个 Dashboard_Diagram
table:
CREATE TABLE Dashboard_Diagram
(
diagram_id TINYINT,
name VARCHAR(50)
)
INSERT INTO Dashboard_Diagram
SELECT 1, 'Radar'
UNION ALL
SELECT 2, 'Bar'
UNION ALL
SELECT 3, 'Pie'
我有 Dashboard_Configuration
table:
CREATE TABLE SomeTable
(
user_id UNIQUEIDENTIFIER,
diagram_id TINYINT
)
和@user_id
:
DECLARE @user_id UNIQUEIDENTIFIER = 'E4F77F2C-8AA1-493A-94A3-03EA212453D4'
我想根据 Dashboard_Diagram
中的行动态地将行插入 Dashboard_Configuration
。所以静态这看起来像:
INSERT INTO Dashboard_Configuration
@userId, 1
. . .
我试过了:
INSERT INTO Dashboard_Configuration
@user_id, (SELECT diagram_id FROM Dashboard_Diagram)
但这会引发错误,因为子查询 returns 有多个值:
Msg 512, Level 16, State 1, Line 7
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
如何根据来自另一个 table 的动态行数插入 table?
使用insert . . . select
:
INSERT INTO Dashboard_Configuration (User_id, name)
SELECT @user_id, name
FROM Dashboard_Diagram;
请注意,这也明确列出了列。名称可能不正确(您没有在问题中指定它们),但最好列出列。
编辑:
上面存在类型冲突。你真的打算这样做吗?
INSERT INTO Dashboard_Configuration (User_id, diagram_id)
SELECT @user_id, dd.diagram_id
FROM Dashboard_Diagram dd;