如何在sql中包含参数名称作为列的名称

时间:2013-12-10 16:36:22

标签: sql-server tsql sql-server-2012

我有一个看起来像这样的存储过程:

CREATE PROCEDURE [dbo].[spRS_Get] 
@Year Varchar(20),
@Month Varchar(20)


AS
BEGIN

SET NOCOUNT ON;

DECLARE @Paramdate datetime; 
DECLARE @ParamYear varchar(4);
DECLARE @ParamMonth varchar(2); 
DECLARE @Concatt varchar(10);
SET     @ParamYear = @Year;
SET     @ParamMonth = @Month;
SET     @Concatt = @ParamMonth + '-' + '01' + '-' + @ParamYear;
SET     @Paramdate = CONVERT(datetime, @Concatt);

SELECT Item
      ,SUM(CASE WHEN [MONTH]  = month(@ParamDate) THEN Sales END) AS month(@ParamDate)
      ,SUM(CASE WHEN  [MONTH] = month(@ParamDate) - 1 THEN Sales END) AS month(@ParamDate) - 1,
      ,SUM(CASE WHEN  [MONTH] = month(@ParamDate) THEN Sales END) - SUM(CASE WHEN [MONTH] = month(@ParamDate) - 1 THEN Sales END) AS  month(@ParamDate) - month(@ParamDate) - 1
FROM ABC
GROUP BY Item

在上面的查询中, AS 之后的部分会导致错误。 我想使用参数名称作为列的名称,但它给了我一个错误。有没有办法可以使用 参数名称作为月份的名称?

1 个答案:

答案 0 :(得分:1)

您只能通过将select语句构建为字符串然后使用sp_executesql命令执行它来完成此操作。

所以你会得到这样的东西:

declare @month0 varchar(2) = cast(month(@paramdate) as varchar(2));
declare @month1 varchar(2) = cast((month(@ParamDate) - 1) as varchar(2));
declare @month2 varchar(2) =
    cast((month(@ParamDate) - month(@ParamDate) - 1) as varchar(2));

declare s nvarchar(1024) =
  'SELECT Item
       , SUM(CASE WHEN [MONTH]  = month(@d) THEN Sales END)
         AS ''' + @month0 +
   ''' , SUM(CASE WHEN  [MONTH] = month(@d) - 1 THEN Sales END)
         AS ''' + @month1 +
   ''' , SUM(CASE WHEN  [MONTH] = month(@d) THEN Sales END) -
         SUM(CASE WHEN [MONTH] = month(@d) - 1 THEN Sales END)
         AS ''' + @month2 +
   ''' FROM ABC GROUP BY Item';

EXEC sp_executesql @s, N'@d DATETIME', @ParamDate;