将名称 - 值对表转换为名称为列的单行表,而不对列名进行硬编码

时间:2017-02-06 19:52:33

标签: sql-server tsql

也许xml函数可以帮助解决这个问题?

我找不到任何不对列名进行硬编码的示例。 我到目前为止:

select * into #temptable from myproc

但是,不幸的是,一个proc的结果,你不能把它变成临时表b / c你不能#NameValuePair

数据

Name Value ---- ----- Color Red Age 43 Mood Happy 看起来像是:

Color Age Mood
----- --- -----
Red   43  Happy

结果如下:

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}}

1 个答案:

答案 0 :(得分:1)

使用提供的参考资料,以下是您可以如何实现的目标

 private void txtPrice_KeyDown(object sender, KeyEventArgs e)
 {
   if (e.Key == Key.Return)
   {
     // UPDATE PRICE HERE 
   }   
}