在SQL SERVER 2012中的COLUMN名称中使用@variable

时间:2016-10-07 16:34:30

标签: sql sql-server loops

在这里,我在TRx1列上使用了SUM函数。 我在表格中列出了TRx2,3,4,... 53列。 我想使用循环显示所有列。

DECLARE @flag INT;
SET @flag = 1;

WHILE @flag <= 2
BEGIN

     select TOP 5 sd.OutletBPID, md.Product, SUM(TRx1)
     from sdata as sd, md, oa
     where sd.PSetID = md.PsetID
     group by sd.OutletBPID, md.Product;

SET @flag = @flag + 1;
END;

我执行了以下代码,但它显示错误:&#34;列名无效&#34;

DECLARE @flag INT;
SET @flag = 1;

WHILE @flag <= 2
BEGIN

     select TOP 5 sd.OutletBPID, md.Product, SUM(TRx@flag)
     from sdata as sd, md, oa
     where sd.PSetID = md.PsetID
     group by sd.OutletBPID, md.Product;

SET @flag = @flag + 1;
END;

1 个答案:

答案 0 :(得分:2)

你需要动态的sql

DECLARE @flag INT,
        @sql varchar(8000)=''
SET @flag = 1;


WHILE @flag <= 2
BEGIN

SET @sql = 'select TOP 5 sd.OutletBPID, md.Product, SUM(TRx'+cast(@flag as varchar(20))+')
            from sdata as sd, md, oa
            where sd.PSetID = md.PsetID
            group by sd.OutletBPID, md.Product'

    exec (@sql)

SET @flag = @flag + 1;
END;