我有一个临时表,需要为不同的客户报告导出字段。该表用作接口:客户端删除并添加字段,我们相应地生成报告。为了便于导出,我们使用以下代码段:
-- Compile select list
select top 1
stuff((
select ',' + 'cast([' + Column + '] as nvarchar(max)) as ' + Column
from #report_fields a
where a.FieldType like 'X' or a.FieldType like 'Y'
for XML path('')
),1,1,'') as document_fields
from #report_fields a
;
这会产生一个类似
的列表cast([Field1] as nvarchar(max)) as Field1,
cast([Field2] as nvarchar(max)) as Field2,
cast([Field3] as nvarchar(max)) as Field3,
...
cast([FieldN] as nvarchar(max)) as FieldN
在
等查询中使用select
cast([Field1] as nvarchar(max)) as Field1,
cast([Field2] as nvarchar(max)) as Field2,
cast([Field3] as nvarchar(max)) as Field3,
...
cast([FieldN] as nvarchar(max)) as FieldN
into
#client_fields_temp
from
dbo.ClientData
我在整个剧本中都这样做。但是,它需要手动运行第一个查询并将结果(字段列表)复制粘贴到第二个查询中。我想自动化这个。是否可以将fieldist存储在变量中并使用以下内容:
-- Compile select list
@fieldlist = select top 1
stuff((
select ',' + 'cast([' + Column + '] as nvarchar(max)) as ' + Column
from #report_fields a
where a.FieldType like 'X' or a.FieldType like 'Y'
for XML path('')
),1,1,'') as document_fields
from #report_fields a
;
select
@fieldlist
into
#client_fields_temp
from
dbo.ClientData
非常感谢任何帮助!