2017-02-06 99 views
0

也許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 
+1

嗯....什麼?... – Lamak

+0

你能張貼NameValue TableFunction和一些預期的輸出?你當然可以通過插入語句將結果存儲在臨時表中。 – scsimon

+1

@scsimon ok現在看 – toddmo

回答

1

使用提供參考,下面是你如何能accomplisht帽子

if object_id('tempdb..#tempValuePair') is not null drop table #tempValuePair 
select 
'Color' as Name, 
'Red' as Value 
into #tempValuePair 
union all 
select 
'Age','43' 
union all 
select 
'Mood','Happy' 



DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) 
DECLARE @ColumnName AS NVARCHAR(MAX) 

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
     + QUOTENAME(Name) 
FROM (SELECT DISTINCT Name FROM #tempValuePair) AS Courses 

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
    N'SELECT ' + @ColumnName + ' 
    FROM #tempValuePair 
    PIVOT(MAX(Value) 
      FOR Name IN (' + @ColumnName + ')) AS PVTTable' 
--Execute the Dynamic Pivot Query 
EXEC sp_executesql @DynamicPivotQuery 
+0

這是非常整潔。你會不會碰巧知道如何將最終結果返回到臨時表中?這是我的嘗試的限制。 – toddmo

+0

由於您不知道執行前會有多少列,因此您必須使用OPENROWSET @toddmo – scsimon

相關問題