也許xml函數對此有幫助?將名稱 - 值對錶轉換爲名稱爲列的單行表,而不對列名進行硬編碼
我找不到任何不難編碼列名的例子。 我能走到今天:
CREATE PROC dbo.OneRowProc
(
@Id DECIMAL(15,0)
)
AS BEGIN
SELECT *
into #NameValuePair
from NameValueTableFunction(@Id)
DECLARE @Sql VARCHAR(MAX) = 'SELECT '
UPDATE #NameValuePair
SET @Sql = @Sql + '''' + Value + ''' AS [' + Name + '],'
SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1)
EXEC (@Sql)
END
GO
但不幸的是,一個進程的結果,你不能讓它到一個臨時表B/C,你不能select * into #temptable from myproc
DATA
#NameValuePair
會是什麼樣子:
Name Value
---- -----
Color Red
Age 43
Mood Happy
結果會是什麼樣子:
Color Age Mood
----- --- -----
Red 43 Happy
UPDATE
我現在能夠得到它到一個臨時表,但我仍然無法得到它到一個表值函數:
IF OBJECT_ID('tempdb..#PolicyInformation') IS NOT NULL
DROP TABLE #PolicyInformation
SELECT
* INTO #PolicyInformation
FROM PolicyInformation(932774264229946)/*60272329046394*/
DECLARE @ColumnDefs AS varchar(max)
--Get distinct values of the PIVOT Column
SELECT
@ColumnDefs = ISNULL(@ColumnDefs + ' VARCHAR(MAX),', '')
+ QUOTENAME(Name)
FROM (SELECT
*
FROM #PolicyInformation) T
SET @ColumnDefs = @ColumnDefs + ' VARCHAR(MAX)'
PRINT @ColumnDefs
IF OBJECT_ID('tempdb..#PolicyInformationTable') IS NOT NULL
DROP TABLE #PolicyInformationTable
CREATE TABLE #PolicyInformationTable (
Dummy int
)
DECLARE @Columns varchar(max),
@AlterTable varchar(max)
SET @AlterTable = 'ALTER TABLE #PolicyInformationTable ADD ' + @ColumnDefs
EXEC (@AlterTable)
ALTER TABLE #PolicyInformationTable DROP COLUMN Dummy
SELECT
*
FROM #PolicyInformationTable
SELECT
@Columns = ISNULL(@Columns + ',', '')
+ '''' + Value + ''' as ' + QUOTENAME(Name)
FROM #PolicyInformation
PRINT @Columns
EXEC ('INSERT #PolicyInformationTable SELECT ' + @Columns)
SELECT
*
FROM #PolicyInformationTable
嗯....什麼?... – Lamak
你能張貼NameValue TableFunction和一些預期的輸出?你當然可以通過插入語句將結果存儲在臨時表中。 – scsimon
@scsimon ok現在看 – toddmo