输入变量作为存储过程语句

时间:2012-02-04 02:05:52

标签: sql-server vb.net variables stored-procedures

我的存储过程:

ALTER PROCEDURE [dbo].[Perdate]
@D_Data as nvarchar(999) 

AS

SELECT    'Total'=  SUM(CAST(TBL_Stock.R_TotalPrice  as decimal(18,2))),(convert(varchar,TBL_Stock.D_Datepush,105)) as Date
FROM       TBL_Stock 
GROUP BY  (convert(varchar,TBL_Stock.D_Datepush,105)) 
Having     (convert(varchar,TBL_Stock.D_Datepush,105)) = @D_Data 

我想知道是否可以将该变量(@D_Data)设置为:

 '02-03-2012' or  (convert(varchar,TBL_Stock.D_Datepush,105)) = '02-04-2012'

所以having子句是:

 HAVING (convert(varchar, TBL_Stock.D_Datepush, 105)) = '02-03-2012' 
        OR (convert(varchar, TBL_Stock.D_Datepush, 105)) = '02-04-2012'

所以我的想法是(在我的VB.net项目中)一个可以动态更改存储过程“Future”的字符串

1 个答案:

答案 0 :(得分:0)

似乎你想要进行SQL注入,以便你的输入参数“粘合”到你的proc中构建的TSQL。这是一个非常糟糕的想法(see SQL Injection discussion here)。

但好消息是,不需要动态SQL。使用表函数来解析传入的字符串,以便它可以在proc中加入。

create table TBL_Stock(R_TotalPrice decimal(18,2), D_Datepush datetime)
insert into TBL_Stock(R_TotalPrice,D_datepush) values(1000,'1/1/2012')
insert into TBL_Stock(R_TotalPrice,D_datepush) values(200,'1/2/2012')
insert into TBL_Stock(R_TotalPrice,D_datepush) values(30,'1/3/2012')
insert into TBL_Stock(R_TotalPrice,D_datepush) values(4,'1/4/2012')
GO

CREATE FUNCTION dbo.SplitDates(@String varchar(8000), @Delimiter char(1))     
returns @temptable TABLE (dt datetime)     
as     
begin     
    declare @idx int     
    declare @slice varchar(8000)     

    select @idx = 1     
        if len(@String)<1 or @String is null  return     

    while @idx!= 0     
    begin     
        set @idx = charindex(@Delimiter,@String)     
        if @idx!=0     
            set @slice = left(@String,@idx - 1)     
        else     
            set @slice = @String     

        if(len(@slice)>0 AND isDate(@slice) = 1)
            insert into @temptable(dt) values(@slice)     

        set @String = right(@String,len(@String) - @idx)     
        if len(@String) = 0 break     
    end 
return     
end
GO

--test function
select * from dbo.SplitDates('1/1/2012,1/2/2012',',')
GO

create PROCEDURE Perdate @D_Data as nvarchar(2000) 
AS
select
    PushDate=z.dt,
    'Total'=  SUM(s.R_TotalPrice)
from 
    dbo.splitDates(@D_Data,',') z
    join TBL_Stock s on s.D_datepush = z.dt
group by
    z.dt
GO

--Test proc
select * from TBL_Stock
exec Perdate '1/1/2012'
exec Perdate '1/1/2012,1/2/2012'
exec Perdate '1/1/2012,1/4/12'

enter image description here