看到原來項目的存儲過程判斷一層套一層,而我則想要盡量簡化,于是網(wǎng)查到下面的寫法,也是緣分,開始就看到了這個比較簡單的寫法,但是思路很新穎,用到了coalesce(返回其參數(shù)中的第一個非空表達式),如果是空,就不返回了。如果不用這個,那么為空的變量也在SQL語句中,將會執(zhí)行錯誤。
最初看到這個代碼很高興,copy來試驗,但是確報錯,+''' 有錯誤,于是用了一般的語句,包含了變量,發(fā)現(xiàn)字符串變量在SQL中要加上引號:'@bzw ',如果和其他字符串連接,就要再加', 成為這樣:''+@bzw+'',如果外層還有引號,則,這里就變成:'''+@bzw+'''.
終于好了,時間字段的初值成了問題,最后發(fā)現(xiàn),傳入的那個變量其實是個字符串型,不是時間型。
總算過關(guān)!看來,相信自己,從小處開始試驗,總能找到強大難題的突破口?。?!
ALTER PROCEDURE dbo.HnMessage
(
--是否處理標志,1:已處理
@bzw char(1)=null,
--報警日期
@sasj2begin nvarchar(80)=null,
@sasj2end nvarchar(80)=null,
--報警電話
@barlxdh7 nvarchar(80)=null,
--接電人
@cjr1 nvarchar(50)=null,
--報警類型
@ajly4 nvarchar(200)=null,
--登錄用戶所在單位
@departname varchar(50)=null
)
AS
declare @sql nvarchar(4000)
set @sql=coalesce(@sql, ' ')+
( ' bzw = '''+@bzw+''' and ', ' ') +
coalesce( ' sasj2 >= '''+@sasj2begin+''' and ', ' ')+
coalesce( ' sasj2 <= '''+@sasj2end+''' and ', ' ')+
coalesce( ' barlxdh7='''+@barlxdh7+ ''' and ', ' ')+
coalesce( ' cjr1='''+@cjr1+ ''' and ', ' ')+
coalesce( ' ajly4='''+@ajly4+ ''' and ', ' ')+coalesce( ' cjdw1 = '''+@departname+''' or ', ' ')+
coalesce( ' bzw = '''+@bzw+''' and ', ' ') +
coalesce( ' sasj2 >= '''+@sasj2begin+''' and ', ' ')+
coalesce( ' sasj2 <= '''+@sasj2end+''' and ', ' ')+
coalesce( ' barlxdh7='''+@barlxdh7+ ''' and ', ' ')+
coalesce( ' cjr1='''+@cjr1+ ''' and ', ' ')+
coalesce( ' ajly4='''+@ajly4+ ''' and ', ' ')+coalesce( ' cjdw2 = '''+@departname+''' and ', ' ')
if len(@sql)> 0 set @sql= ' where '+left(@sql,len(@sql)-4)
--打印出來自己看吧
print @sql
set @sql= 'SELECT [BH0], [ID], [BARXM5], [BARDWHZZ8], [SASJ2], [BARLXDH7],'+
'[FXSJ10], [AJLY4], [ss_ajdl], [ss_ajnb], [JYAQ39], [duty_name],'+
'[ldps], [DXCADDMAN], [cjsj2], [cjdw2], [cjsj1], [cjdw1], [ss_ajyy],'+
'[AJCLQK], [ysbm], [sldw], [CJJG], [SDCJR], [NEW_FADD], [ss_faqy], [cjr1], [cjr2] FROM [DXC_BJAJDJB20] '+@sql
exec(@sql)