日期:2014-05-18  浏览次数:20463 次

求解一个多条件中确定每一个条件是否为空然后决定进行哪一步操作的存储过程
有一个存储过程有3个输入参数,分别是@companname,@startdate,@enddate;代表的是公司名称,开始时间,结束时间,现在的要求是:
这3个参数各都有为空和不为空二种状态,组合起来就有N种结果,如果一条条写出来,应该比较麻烦,求高手看一下如何写出这种存储过程。

下面这个是全部不为空的写法
————————————————————————————————————
                        select   公司id,公司名称,sum(金额)   as   总额   from
                                    (
                                      select   *   from   1   where   请求时间   <   @enddate   and   请求时间   >   @startdate
                                      union   all
                                      select   *   from   2   where   请求时间   <   @enddate   and   请求时间   >   @startdate
                                    )   t   where   审批意见= '同意 '   and   公司名称=@companyname
                      group   by   公司id,公司名称   order   by   公司id
————————————————————————————————————


下面这个是全部为空的写法
————————————————————————————————————
                        select   公司id,公司名称,sum(金额)   as   总额   from
                                    (
                                      select   *   from   1                                      
                                      union   all
                                      select   *   from   2                                       )   t   where   审批意见= '同意 '                         group   by   公司id,公司名称   order   by   公司id
————————————————————————————————————

可能还需要注意的是要判断开始时间和结束时间是否正确,请高手帮个忙吧!

------解决方案--------------------
用动态SQL。

如:

declare @p1 int, @p2 int, @p3 int, @sql varchar(8000)

set @sql = 'select * from 表名 where 1=1 '
if @p1 is not null
set @sql = @sql + ' and 字段1= ' + cast(@p1 as varchar(100))

if @p2 is not null
set @sql = @sql + ' and 字段1= ' + cast(@p2 as varchar(100))

if @p3 is not null
set @sql = @sql + ' and 字段1= ' + cast(@p3 as varchar(100))

exec (@sql)