我有一个在字段中有数字的表。基于该数字,我希望SQL将记录插入到另一个表中。下面是第一个表的示例:
Event Fields Type
Swimming 3 Basic
Swimming 2 Advanced
Running 5 Basic
Running 1 Advanced
所以根据上面的表格,我希望SQL能够插入下面的记录:
Event GradeType Grade
Swimming Basic1 NULL
Swimming Basic2 NULL
Swimming Basic3 NULL
Swimming Advanced1 NULL
Swimming Advanced2 NULL
Running Basic1 NULL
Running Basic2 NULL
Running Basic3 NULL
Running Basic4 NULL
Running Basic5 NULL
Running Advanced1 NULL
我想我需要使用WHILE来循环,但还没有线索从哪里开始!所有帮助表示赞赏。
答案 0 :(得分:5)
根本不需要循环:
INSERT INTO new_table(Event, GradeType, Grade)
SELECT Event, CONCAT(Type, n) AS [GradeType], NULL AS Grade
FROM tab
CROSS APPLY (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9)) AS n(n)
WHERE n <= Fields;
的 LiveDemo
强>
请记住,n
子查询是带有硬编码值的计数表。您可以使用任何其他合适的方法。相关:What is the best way to create and populate a numbers table?
如果您使用SQL Sever
低于2012,则需要使用+
进行连接。
答案 1 :(得分:1)
刚建立Lad2025答案。如果你低于2012年(特别是2005年,因为不支持值条款),你可以使用下面的查询。假设你有数字表,否则这里是通往populate it的方式
SELECT Event,
Type+ cast(n as varchar(5)) AS [GradeType],
NULL AS Grade
FROM tab t
CROSS APPLY (select n from numbers nmbr where nmbr.n<=t.fields) b