首页 > Linux操作系统 > Linux操作系统 > case when遇上null值
利用存储过程对表中记录进行update,是很常见,也很容易的,但是如果更新的表有字段是允许null的、需要对是否为null做不同处理,同时该存储过程的执行命令是用sp_executesql,你会怎么处理呢,相信很多人第一时间想到的也是在update语句里用case when吧。如果你也是这样想,并这么做的话,相信你肯定郁闷的发现:
1、case when判断null值,得到相反的结果,只有是常量值的情形,执行时正常的;
2、sql server对拼接的字符串形式的sql语句中的错误,不提示错误信息,除了罢工;
case when的执行结果跟我们预期的相反。请见如下脚本:
(另外发现,sql
server里对拼接得到的字符串sql语句里面的错误,不做如何报错提示,仅仅是来个不理不问,无任何反映。此次case
when不能正常执行null值的情况,就是我一段一段拼接的sql字符串注释后,检测出来的,汗~~。在这提供一个可用的检测语句print cash null
when null then ‘null’ else ‘not null’ end)
declare @sql nvarchar(2000)
declare @dbName nvarchar(50)
if exists(select 1 from syscfg where isTestDB='' or isTestDB is
null)
begin
--live dataBase
set
@dbName=’dbLive’
end
else
begin
--test dataBase
set
@dbName='dbTest'
end
set @sql='update '+@dbName+'.dbo.PathologyHead set '
----patient部分
+' Birthday='+case @Birthday when null then
'null,' else ''''+cast(@Birthday as nvarchar(20))+''',' end
+' IsHKID='+case @IsHKID when 1 then '1' else '0' end+','
+'
IDType='+cast(@IDType as nvarchar(5))
+' where
LabNumber='''+@LabNumber+''''
--print @sql
exec sp_executesql
@sql
上面的对字段IsHKID的执行却是正常的,难道case when是得对非null的值才行?我将@Birthday值的是否为null,移到前面判断,执行正常,修改后的如下:
set @Birthday=isnull(@Birthday,'1910-10-1') --移到下面的update中处理
set @sql='update '+@dbName+'.dbo.PathologyHead set '
----patient部分
+' Birthday='+case @Birthday when '1910-10-1'
then 'null,' else ''''+cast(@Birthday as nvarchar(20))+''',' end
+' IsHKID='+case @IsHKID when 1 then '1' else '0'
end+','
+' IDType='+cast(@IDType as nvarchar(5))
+' where LabNumber='''+@LabNumber+''''
--print @sql
exec
sp_executesql @sql
原文地址:http://www.cnblogs.com/hyqiang168/archive/2009/10/16/1584424.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/16436858/viewspace-616718/ ,如需转载,请注明出处,否则将追究法律责任。