SQL Server中动态字段的转换

时间:2018-06-12 10:40:21

标签: sql sql-server sql-server-2008-r2

根据以下场景,我如何从View实现此输出。

input Tables

Output

我只是以这种方式尝试

SELECT ',DynamicField'+ CAST(Seq AS NVARCHAR(10)) + ' as ' 
+ '['+ FieldName + ']' FROM dbo.Feilds
 WHERE FieldName IS NOT null FOR XML PATH('') ) 

以上查询RETURNS

 ,DynamicField1 as [Name],DynamicField2 as [Fname],DynamicField3 as [Lname]
 ,DynamicField4 as [Gender],DynamicField5 as [Country] 





SELECT id,Employeeid,DynamicField1 as [Name]
  ,DynamicField2 as [Fname],DynamicField3 as [Lname]
  ,DynamicField4 as [Gender],DynamicField5 as [Country] FROM TransactionDetails

1 个答案:

答案 0 :(得分:0)

尝试这样,在[]

中包含列名
SELECT ','+'['+'DynamicField'+ CAST(Seq AS NVARCHAR(10)) + ' as ' 
+ FieldName + ']' FROM dbo.Feilds
 WHERE FieldName IS NOT null FOR XML PATH('')