是否可以在存储过程的参数中放置列名?

时间:2012-08-16 08:00:43

标签: sql-server-2008

我有一张类似于下面的表

Date   |field1  | qty1 | qty2 | qty3
1 Aug  | xyz    | 0    | 0    | 3
1 Aug  | xyz    | 3    | 0    | 0
1 Aug  | abc    | 0    | 5    | 0
2 Aug  | abc    | 0    | 15   | 0
2 Aug  | xyz    | 0    | 12   | 0
2 Aug  | xyz    | 5    | 0    | 0

我已经编写了三个存储过程来分别显示每个数量。

这是我的第一个程序

create procedure firstprocedure 
@startdate datetime, @enddate datetime
As
select date, sum (case when field1 = 'xyz', qty1) as XYZ,
sum (case when field1 = 'abc', qty1) as ABC 
from table1
where date between @startdate and @enddate
group by date

这是我的第二个程序

Create procedure secondprocedure
@startdate datetime, @enddate datetime
As
select date, sum (case when field1 = 'xyz', qty2) as XYZ,
sum (case when field1 = 'abc', qty2) as ABC 
from table1
where date between @startdate and @enddate
group by date

这是我的第三个程序

Create procedure thirdprocedure 
@startdate datetime, @enddate datetime
As
select date, sum (case when field1 = 'xyz', qty3) as XYZ,
sum (case when field1 = 'abc', qty3) as ABC 
from table1
where date between @startdate and @enddate
group by date

我想我是否有机会将列(无论是qty1,qty2还是qty3)放在参数中,而在执行时只需要提及qty1或qty2或qty3。它应相应地产生输出。

2 个答案:

答案 0 :(得分:1)

试试这个:

创建一个这样的过程:

create procedure my_procedure(@startdate datetime, @enddate datetime,@qty_type varchar(50))
as
begin 
    with cte as( 
    select 'qty1' [col_name],date, sum (case when field1 = 'xyz' then qty1 end) as XYZ,
    sum (case when field1 = 'abc' then qty1 end) as ABC 
    from table1
    where date between @startdate and @enddate
    group by date
    union all 
    select 'qty2' [col_name],date, sum (case when field1 = 'xyz' then qty2 end) as XYZ,
    sum (case when field1 = 'abc' then qty2 end) as ABC 
    from table1
    where date between @startdate and @enddate
    group by date
    union all
    select 'qty3' [col_name],date, sum (case when field1 = 'xyz' then qty3 end) as XYZ,
    sum (case when field1 = 'abc' then qty3 end) as ABC 
    from table1
    where date between @startdate and @enddate
    group by date
    )select * from cte where [col_name]=@qty_type
end

然后执行:

exec '2012-04-01','2012-05-01','qty1'

exec '2012-04-01','2012-05-01','qty2'

答案 1 :(得分:1)

您可以使用动态SQL,如下所示:

CREATE PROCEDURE procedureName
    @ColumnName NVARCHAR(100),
    @startdate datetime, 
    @enddate datetime
AS
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = N'
    select date, sum (case when field1 = ''''xyz'''', ' + @ColumnName + ') as XYZ,
    sum (case when field1 = ''''abc'''', ' + @ColumnName + ') as ABC 
    from table1
    where date between ' + CONVERT(DateTime, @startdate, 101) + 
        ' and ' + CONVERT(DateTime, @enddate, 101) +
    'group by date'

EXEC(@SQL)

您可以这种方式调用存储过程(来自SQL):

EXEC procedureName 'qty1', '01/01/2012', '01/01/2011'

注意

在我使用CONVERT(DateTime, @startdate, 101)的地方,您必须更改样式值(当前为101),以满足您对所用日期格式的要求。有关详细信息,请参阅此页面:MSDN CONVERT