答案 0 :(得分:4)
使用cross apply()
与values()
联系以取消您的数据:
select v.Machine, v.Temperature, v.Humidity, t.Fecha
from t
cross apply (values ('DR673',DR673_T,DR673_H),('DR677',DR677_T,DR677_H)
) as v(Machine, Temperature, Humidity)
根据列名动态生成sql:
declare @cols nvarchar(max), @sql nvarchar(max);
set @cols = stuff((
select distinct
',(''' + left(C.name,charindex('_',c.name)-1)
+ ''','+ quotename(C.name)
+ ','+ quotename(left(C.name,charindex('_',c.name))+'H')
+')'
from sys.columns c
where c.object_id = object_id('dbo.t')
and c.name like '%_T'
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'');
set @sql = '
select v.Machine, v.Temperature, v.Humidity, t.Fecha
from t
cross apply (values '+@cols+'
) as v(Machine, Temperature, Humidity)';
select @sql as CodeGenerated;
--exec sp_executesql @sql; /* to execute the dynamic sql */
rextester演示:http://rextester.com/NAOT80053
返回:
+---------------------------------------------------------------------------------------+
| CodeGenerated |
+---------------------------------------------------------------------------------------+
| select v.Machine, v.Temperature, v.Humidity, t.Fecha |
| from t |
| cross apply (values ('DR673',[DR673_T],[DR673_H]),('DR677',[DR677_T],[DR677_H]) |
| ) as v(Machine, Temperature, Humidity) |
+---------------------------------------------------------------------------------------+