sql服务器将声明的变量分配给列名

问题描述 投票:0回答:1

是否可以执行以下操作?

declare @start_date int
declare @end_date int

set @start_date = 202003
set @end_date = 202004

select
    'Total_Units' as Metric_Description
    ,cast(count(*) as varchar(max)) as @end_date
from table

我正在尝试使用@end_date作为查询结果中列的名称,换句话说,我试图做到这一点,而每个月所有多个查询中的202004都没有更改

select
    'Total_Units' as Metric_Description
    ,cast(count(*) as varchar(max)) as '202004'
from table
sql-server-2008 variables declare
1个回答
0
投票
declare @start_date int declare @end_date varchar(20) set @start_date = 202003 set @end_date = '202004' declare @query varchar(max) set @query = 'select ''Total_Units'' as Metric_Description ,cast(count(*) as varchar(max)) as [' + @end_date + '] from table' exec sp_sqlexec @query
© www.soinside.com 2019 - 2024. All rights reserved.