如何使用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%'
答案 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