如何将列标题为SQL中的变量?

时间:2014-10-20 19:37:53

标签: sql-server tsql

SQL的新手,需要一些帮助。我试图将变量用作列标题,并在一定范围内迭代求和值。这是以下代码。

DECLARE @startmonth AS INT
DECLARE @endmonth AS INT
DECLARE @earnedpremiumyear AS INT
SET @startmonth = 200501
SET @endmonth = 200512
SET @earnedpremiumyear = 2005

WHILE @startmonth <= 201301
BEGIN
    SELECT SUM(earnedpremium) AS @earnedpremiumyear
    FROM dbo.Database
    WHERE accountingmonth BETWEEN @startmonth AND @endmonth
    AND earnedendingmonth BETWEEN @startmonth AND @endmonth
    SET @startmonth = @startmonth + 100
    SET @endmonth = @endmonth + 100
    SET @earnedpremiumyear = @earnedpremiumyear + 1
END

我想要它以便SUM的标题是获得的保费年度,从2005年开始到2013年。当我运行此代码时,我收到此错误:

  

&#39; @ earnpremiumyear&#39;

附近的语法不正确

所以我确实错误地称这个变量。有人可以帮忙吗?

另外,我如何制作它,而不是为每年的总数创建一个表,总和都在一列或一行的一个表上?

谢谢!

3 个答案:

答案 0 :(得分:4)

您可以尝试将其简化为以下内容吗?

SELECT 
    LEFT(CAST(AccountingMonth AS VARCHAR(4)),4) AS AccountingYear,
    SUM(EarnedPremium) AS TotalEarnedPremium
FROM Database.dbo.Table 
WHERE 
    AccountingMonth BETWEEN 200501 AND 201301 AND 
    EarnedEndingMonth BETWEEN 200501 AND 201301 
GROUP BY LEFT(CAST(AccountingMonth AS VARCHAR(4)),4) 

答案 1 :(得分:0)

我能想到的唯一方法是编写动态SQL查询:

DECLARE @startmonth AS INT
DECLARE @endmonth AS INT
DECLARE @earnedpremiumyear AS INT
SET @startmonth = 200501
SET @endmonth = 200512
SET @earnedpremiumyear = 2005
DECLARE @sql VARCHAR(MAX) = '';


WHILE @startmonth <= 201301
    BEGIN
    SELECT @sql = 'SUM(earnedpremium) AS ' + @earnedpremiumyear
    + 'FROM dbo.Database
    WHERE accountingmonth BETWEEN' + @startmonth + ' AND ' + @endmonth
    ...
    EXEC(@sql)
END

但这可能会变得非常丑陋。

答案 2 :(得分:0)

有些事情可以解决这个问题..

DECLARE @f   VARCHAR(10)='fff',
        @sql NVARCHAR(max)

SET @sql ='select 1 as ' + @f 

EXEC Sp_executesql
  @sql