我有一张ID_DATA表,下面有记录
3 test
5 tested
我需要生成一个插件sql,如下所示
insert into ID_DATA_QURY values ('test');
insert into ID_DATA_QURY values ('test');
insert into ID_DATA_QURY values ('test');
insert into ID_DATA_QURY values ('tested');
insert into ID_DATA_QURY values ('tested');
insert into ID_DATA_QURY values ('tested');
insert into ID_DATA_QURY values ('tested');
insert into ID_DATA_QURY values ('tested');
输出应该基于_ID中的值,前3个插入基于值3和数据"测试"接下来是5"测试"
首先需要你的帮助或示例。
答案 0 :(得分:1)
从SQL Server 2008,您可以使用CROSS APPLY
表运算符:
DECLARE @T TABLE (ID INT, DATA VARCHAR(10))
INSERT INTO @T
SELECT 3, 'Test' UNION
SELECT 5, 'Tested'
SELECT 'insert into ID_DATA_QURY values (' + T.DATA + ');' AS Command
FROM @T AS T
CROSS APPLY (SELECT N
FROM (SELECT 1 AS N UNION
SELECT 2 UNION
SELECT 3 UNION
SELECT 4 UNION
SELECT 5) AS I
WHERE N <= T.ID) AS M
ORDER BY T.ID;
<强>更新强>
否则在以前版本的SQL Server中使用它(也应该在MySQL上使用):
DECLARE @T TABLE (ID INT, DATA VARCHAR(10))
DECLARE @I TABLE (N INT)
INSERT INTO @T (ID, DATA)
VALUES (3, 'Test')
,(5, 'Tested')
-- You can replace it with a table filled with integer numbers.
INSERT INTO @I (N)
VALUES (1),(2),(3),(4),(5)
SELECT 'insert into ID_DATA_QURY values (' + T.DATA + ');' AS Command
FROM @T AS T
CROSS JOIN (SELECT N
FROM @I) AS M
WHERE N <= T.ID
ORDER BY T.ID;
根据需要进行调整。