是你要找的吗?
SQL小提琴
MS SQL Server 2008 架构设置:
CREATE TABLE TempA
(columnName varchar(2))
;
INSERT INTO TempA
(columnName)
VALUES
('T1'),
('T2'),
('T3'),
('T4')
;
CREATE TABLE TempXmlData
(T1 varchar(1), T2 varchar(1), T3 varchar(1), T4 varchar(1))
;
INSERT INTO TempXmlData
(T1, T2, T3, T4)
VALUES
('A', 'B', 'C', 'D')
;
查询 1:
DECLARE @colTable table(rownum int, columnName varchar(20))
INSERT INTO @colTable SELECT row_number() over (ORDER BY columnName), columnName FROM TempA
DECLARE @query varchar(500)
DECLARE @i int, @max int
SET @i = 1
SET @max = (SELECT count(*) FROM @colTable)
SET @query = 'select '
WHILE @i <= @max
BEGIN
IF @i > 1 SET @query = @query + ','
SET @query = @query + (SELECT columnName FROM @colTable WHERE rownum = @i)
SET @i = @i + 1
END
SET @query = @query + ' from TempXmlData'
exec(@query)
结果:
| T1 | T2 | T3 | T4 |
|----|----|----|----|
| A | B | C | D |