日期:2014-05-17  浏览次数:20585 次

存储中变量怎么写?
存储过程中
定义了2个变量
@BegDate  
@EndDate
@SQL
我想如果这个两个变量为空则查询所有的记录
SET @SQL ='1=1'
IF (@BegDate<>''AND @EndDate<>'')
SET @SQL=@SQL+' and AccDate between '+@BegDate+' and ' + @EndDate
如:select WarehouseID,AccDate,SUM(SaleAmt) AS Saleamt from #T where AccDate between @BegDate and @EndDate group BY WarehouseID,AccDate

select WarehouseID,AccDate,SUM(SaleAmt) AS Saleamt from #T where +@sql group BY WarehouseID,AccDate
这样要报错的 请问一下这个语句怎么写呢?

------解决方案--------------------
set @sql=''
IF (@BegDate<>''AND @EndDate<>'')
begin
SET @SQL=@SQL+' where AccDate between '+@BegDate+' and ' + @EndDate
end
exec ('select WarehouseID,AccDate,SUM(SaleAmt) AS Saleamt from #T '+@sql+' group BY WarehouseID,AccDate')

这样试试呢
------解决方案--------------------
可以用if判断,也可以用isnull处理一下。
------解决方案--------------------
select WarehouseID,AccDate,SUM(SaleAmt) AS Saleamt from #T where 
AccDate >=case when isnull(@BegDate,'')='' then AccDate else  @BegDate end
and AccDate <=case when isnull(@EndDate,'')='' then AccDate else  @EndDate end

仅供参考!
------解决方案--------------------
case when也可以啊
http://blog.csdn.net/dba_huangzj/article/details/7684520广告时间