简体   繁体   中英

How to insert into a table based on a multi-row subquery?

I have a 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'

I have Dashboard_Configuration table:

CREATE TABLE SomeTable
(
    user_id UNIQUEIDENTIFIER,
    diagram_id TINYINT
)

And @user_id :

DECLARE @user_id UNIQUEIDENTIFIER = 'E4F77F2C-8AA1-493A-94A3-03EA212453D4'

I want to dynamically insert rows into Dashboard_Configuration , based on the rows in Dashboard_Diagram . So statically this would look like:

INSERT INTO Dashboard_Configuration
@userId, 1
. . . 

I have tried:

INSERT INTO Dashboard_Configuration
@user_id, (SELECT diagram_id FROM Dashboard_Diagram)

But this throws an error because the subquery returns more than one value:

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.

How can I insert into a table, based on a dynamic amount of rows from another table?

Use insert . . . select insert . . . select insert . . . select :

INSERT INTO Dashboard_Configuration (User_id, name)
    SELECT @user_id, name
    FROM Dashboard_Diagram;

Note that this also lists the columns explicitly. The names may not be correct (you don't specify them in the question), but it is a best practice to list the columns.

EDIT:

There is a type conflict above. Do you really intend this?

INSERT INTO Dashboard_Configuration (User_id, diagram_id)
    SELECT @user_id, dd.diagram_id
    FROM Dashboard_Diagram dd;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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