例如,我有第一个表,我想使用第一个表填充第二个表。
Table A
Name A B C D
-----------------------
name1 a1 b1 c1 d1
name2 a2 b2 c2 d2
Table B (Desired Format)
ID Name Code
----------------------
1 name1 a1
2 name1 b1
3 name1 c1
4 name1 d1
5 name2 a2
6 name2 b2
7 name2 c2
8 name2 d2
根据@Surendra Nath GM 的建议,我尝试了这个
DECLARE @counter as int
SET @counter = 1;
;WITH Actual AS
(
SELECT ROW_NUMBER() OVER( ORDER BY IDKEY) as ID FROM Northwind.dbo.Table1
WHERE
),FIRST AS
(
SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4-3) AS ID,Name, A
FROM Northwind.dbo.Table1
),SECOND AS
(
SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4-2) AS ID, Name ,B
from Northwind.dbo.Table1
), NEXT AS
(
SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4-1) AS ID, Name, C
from Northwind.dbo.Table1next
), ________ as
(
SELECT ((ROW_NUMBER() OVER( ORDER BY IDKEY))*4) AS ID, Name, D
from Northwind.dbo.Table1
)
@counter = @counter+1;
)
SELECT * FROM FIRST
UNION ALL
SELECT * FROM SECOND
UNION ALL
SELECT * FROM NEXT
UNION ALL
SELECT * FROM _________
ORDER BY ID
在这里,我在“SECOND AS”之后使用什么。我尝试编写“THIRD AS”,但显然不存在这样的命令,因此经过一番搜索,我可以使用“NEXT AS”编写第三行,但我完全不知道如何插入第四行。
我知道我可以简单地为 A、B、C 和 D 中的每一个编写 4 个插入命令,但是我将按以下顺序获得非代码,这是不需要的:
Table B(NOT DESIRED IN THIS FORMAT)
ID Name Code
----------------------
1 name1 a1
2 name2 a2
3 name1 b1
4 name2 b2
5 name1 c1
6 name2 c2
7 name1 d1
8 name2 d2
此外,可以使用简单的循环来实现所需的格式,但在我正在处理的项目中,大约有 200000 行,简单的循环方法需要很多时间。所以,我想用 CTE 来做。请帮忙。