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

存储过程中变量为空应当如何?
SET @sql_word= 'insert into '+@ResultTable +'
select distinct EXITSTATION,11,exitdate,RECORDTYPE,vehicleclass,totaltoll
from '+@BaseTable+' 
where EXITSTATION = '+@Station+'
GROUP BY exitdate,EXITSTATION,RECORDTYPE,vehicleclass,totaltoll
order by EXITSTATION,exitdate,RECORDTYPE,vehicleclass,totaltoll'
print(@sql_word)
exec(@sql_word)


如果我的@Station 为空,这个代码便会报错,请问怎样表现才会让我@Station 变量为空时跳过这行?

------解决方案--------------------

if @Station <>''
begin
SET @sql_word= 'insert into '+@ResultTable +'
                            select distinct EXITSTATION,11,exitdate,RECORDTYPE,vehicleclass,totaltoll
                            from '+@BaseTable+' 
                            where EXITSTATION = '+@Station+'
                            GROUP BY exitdate,EXITSTATION,RECORDTYPE,vehicleclass,totaltoll
                            order by EXITSTATION,exitdate,RECORDTYPE,vehicleclass,totaltoll'
end
就这样改。再试试
------解决方案--------------------
try this,

SET @sql_word= 'insert into '+@ResultTable
             +' select distinct EXITSTATION,11,exitdate,RECORDTYPE,vehicleclass,totaltoll '
             +' from '+@BaseTable 
             +' where 1=1 '+case when @Station<>'' then ' and EXITSTATION='''+@Station+''' ' else '' end