所以就查詢了一下,目前有兩種方式
1.使用PIVOT, 轉置table, 但是原始column name 不能跟欄位裡面的值重複, 不然會出錯
說明: 先動態取得要轉置成column的欄位, ColumnGroup , 組成需要的字串, 再用PIVOT轉置TABLE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @ColumnGroup NVARCHAR(MAX), @PivotSQL NVARCHAR(MAX) | |
SELECT @ColumnGroup = COALESCE(@ColumnGroup + ',' ,'' ) + QUOTENAME([Name]) | |
FROM dbo.[TCILanguage] | |
GROUP BY QUOTENAME([Name]) | |
select @ColumnGroup | |
SELECT @PivotSQL = N' | |
SELECT * FROM (SELECT l.name FROM dbo.[Language] l) t | |
PIVOT ( | |
-- 設定彙總欄位及方式 | |
MAX(CN) | |
-- 設定轉置欄位,並指定轉置欄位中需彙總的條件值作為新欄位 | |
FOR [Name] IN (' + @ColumnGroup + N') | |
) p;' | |
select @PivotSQL | |
EXEC sp_executesql @PivotSQL; | |
GO |
2.. 第二種方式 直接將某欄位用 xml path 轉成 xml, 再轉成值, 要注意的是欄位值不能有單引號,因為是組字串的關係,可能會造成sql錯誤
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare @sql nvarchar(max); | |
declare @tmpSql nvarchar(max); | |
set @tmpSql = (select ''''+CN+''' as '''+Name+''',' from [Language] for xml path(''), type).value('.', 'nvarchar(max)') | |
set @sql = 'select ' + left(@tmpSql,len(@tmpSql)-1); | |
select @sql | |
execute (@sql); |