這應該得到的序號位置作爲COL_INDEX和轉換領域Col_Value動態
DECLARE @sql NVARCHAR(MAX),
@columns NVARCHAR(Max),
@ordinals NVARCHAR(Max),
@table VARCHAR(200) = 'table'
SELECT @columns = STUFF ((SELECT ',CAST(' + QUOTENAME(column_name) + ' AS VARCHAR(MAX)) AS ' + QUOTENAME(ORDINAL_POSITION)
FROM information_schema.columns
WHERE [email protected]
ORDER BY ORDINAL_POSITION FOR XML PATH('')), 1, 1, ''),
@ordinals = STUFF ((SELECT ',' + QUOTENAME(ORDINAL_POSITION)
FROM information_schema.columns
WHERE [email protected]
ORDER BY ORDINAL_POSITION FOR XML PATH('')), 1, 1, '')
SET @sql = N'
SELECT Col_Index,
Col_Value
FROM (SELECT ' + @columns + ' FROM ' + @table + ') t
UNPIVOT (
Col_Value
FOR Col_Index in (' + @ordinals + ')
) up
'
,如果你有多個模式,您將需要定義與表名一起,和前置一個到您的選擇查詢中的表名
重複http://stackoverflow.com/questions/18026236/sql-server-columns-to-rows – iamdave
請參閱[this](https://technet.microsoft.com /en-us/library/ms177410%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396) – techspider
這些都沒有幫助。我沒有試圖去發現一個價值。我正在努力去發掘每一個價值。 –