--Drop the table if exists
drop proc if exists test_sp
use testdb
go
create procedure test_sp
(@metric varchar(50) = NULL,
@from_date date = NULL,
@to_date date = NULL)
as
begin
set nocount on;
--declaring the column name type
declare @column_name decimal(25,2)
--specifying the column name based on the metric provided
if @metric = 'Sales'
begin
@column_name = 'sales_value'
end
else
begin
@column_name = 'revenue_value'
end
--sum the value based on the metric
select sum(@column_name)
from <dataset>
where metric = @metric
end
-- execute the procedure
exec test_sp @metric = 'sales'
答案 0 :(得分:1)
作为动态sql的替代方法,可以使用case表达式。这将使您的整个过程变得如此简单。
create procedure test_sp
(
@metric varchar(50) = NULL
,@from_date date =NULL
,@to_date date =Null
)
AS
BEGIN
SET NOCOUNT ON;
select sum(case when @metric = 'Sales' then sales_value else revenue_value end) from <dataset> where metric = @metric
END
答案 1 :(得分:0)
这里需要动态SQL。没有它,就不能为对象(表名,列名等)使用变量。
...
declare @sql varchar(max)
--sum the value based on the metric
set @sql = 'select sum(' + @column_name + ') from <dataset> where metric = ' + @metric
print(@sql) --this is what will be executed in when you uncomment the command below
--exec (@sql)
end
--execute the procedure
exec test_sp @metric ='sales'
但是,您可以将它们全部消除...并缩短步骤
use testdb
go
create procedure test_sp
(
@metric varchar(50) = NULL
,@from_date date =NULL
,@to_date date =Null
)
AS
BEGIN
SET NOCOUNT ON;
--specifying the column name based on the metric provided
if @metric = 'Sales'
begin
select sum('sales_value')
from yourTable
where metric = @metric --is this really needed?
end
else
begin
select sum('revenue_value')
from yourTable
where metric = @metric --is this really needed?
end
此外,不确定@from_date
和@to_date
是做什么用的,因为您没有在过程中使用它们。我想他们最终会在WHERE
子句中使用。