SQL使用select的结果插入多个值

时间:2013-12-17 15:50:44

标签: sql

如何使用select的值插入多个值?我想做这样的事情:

INSERT INTO Table1
    (id, value1, value2)
VALUES
    (id1, 1, 1),
    (id1, 3, 1),
    (id1, 4, 1),
    ...
    (id2, 1, 1),
    (id2, 3, 1),
    (id1, 4, 1),
    ...

但我想从select:

获取id1,id2等
SELECT ID
FROM Table2
WHERE name like '%bla%'

2 个答案:

答案 0 :(得分:2)

也许就像这样

INSERT INTO Table1
(id, value1, value2)
SELECT ID,value1, value2
FROM Table2
WHERE value1 like '%bla%'

答案 1 :(得分:0)

DECLARE @ids AS TABLE(id int not null primary key identity(1,1), targetId int)

INSERT INTO @ids (targetId)
    SELECT ID
    FROM Table2
    WHERE name like '%bla%'

DECLARE @i AS int
DECLARE @n AS int
DECLARE @id AS int

SET @n = (SELECT COUNT(1) FROM @ids)
SET @i = 1

WHILE ( @i <= @n )
BEGIN
    SELECT @id = targetId FROM @ids WHERE id = @i

    INSERT INTO Table1
        (ID, Value1, Value2)
    VALUES
        (@id, 1, 1),
        (@id, 4, 1),
        (@id, 5, 1)

    SET @i = @i + 1
END