将键值对转换为列

时间:2018-06-26 08:50:06

标签: sql-server sql-server-2012

这里的代码段结合了给定表中的所有列。

IF OBJECT_ID('tempdb..#temp1') IS NOT NULL
DROP TABLE #temp1

create table #temp1(id float null, value nvarchar(100) null)
insert into #temp1 values(1, 'xyz')
insert into #temp1 values(2, 'pqr')
insert into #temp1 values(null, 'lmn')

select * from #temp1

id                     value
---------------------- ------------
1                      xyz
2                      pqr
NULL                   lmn

DECLARE @sql nvarchar(max)
SELECT @sql = ISNULL(@sql + ')' + '+''|''+ ','') + '''' + c.name + '=''+' + 'convert(nvarchar(max), COALESCE(' + c.name + ', '''')'
FROM tempdb.sys.all_columns c 
WHERE Object_ID = OBJECT_ID('tempdb..#temp1')
SET @sql = 'SELECT ' + @sql + ')+' + ''''' FROM #temp1'
EXEC( @sql)

正确返回结果。

--------------------------------
id=1|value=xyz
id=2|value=pqr
id=0|value=lmn

对于另一个表,结果看起来也不错。

IF OBJECT_ID('tempdb..#temp2') IS NOT NULL
DROP TABLE #temp2

create table #temp2(city nvarchar(100) null, temp1 float null, temp2 float null)
insert into #temp2(city, temp1, temp2) values('new york', 20, 12)
insert into #temp2(city, temp1, temp2) values('chicago', 15, 17)
insert into #temp2(city, temp1, temp2) values('portland', null, 5)

select * from #temp2

city     temp1  temp2
---------------------------- ---------------------- ----------------------
new york 20   12
chicago  15   17
portland NULL 5

结果

city=new york|temp1=20|temp2=12
city=chicago|temp1=15|temp2=17
city=portland|temp1=0|temp2=5

现在,我想做的完全相反,对于给定的键值对,将以列和值格式返回行。

例如

city=chicago|temp1=15|temp2=17
city=portland|temp1=0|temp2=5

city     temp1 temp2
--------------------
chicago  15    17
portland NULL  5

1 个答案:

答案 0 :(得分:1)

您可以通过类似以下操作来实现它:

CREATE TABLE #DYNAMIC (VAL VARCHAR(MAX))

INSERT INTO #DYNAMIC 
VALUES('ID=1|VALUE=XYZ'),('ID=2|VALUE=PQR'),('ID=0|VALUE=LMN')

DECLARE @SQL_BUILD VARCHAR(MAX)='';
SELECT @SQL_BUILD = @SQL_BUILD + VAL FROM (
SELECT  'SELECT ' +REPLACE(VAL,'|','&COMMA&'  )+ ', UNION ALL ' VAL FROM #DYNAMIC
)A

SELECT @SQL_BUILD = REPLACE(@SQL_BUILD,'=','=''');
SELECT @SQL_BUILD = REPLACE(@SQL_BUILD,',','''');
SELECT @SQL_BUILD =REPLACE(@SQL_BUILD,'&COMMA&',''',');
SELECT @SQL_BUILD = SUBSTRING(@SQL_BUILD,1,LEN(@SQL_BUILD)-10)

EXEC(@SQL_BUILD)

结果:

ID  VALUE
---------
1   XYZ
2   PQR
0   LMN