国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 数据库 > Sqlserver > Sql server中Case when遇上null值

Sql server中Case when遇上null值

来源:程序员人生   发布时间:2013-11-15 09:39:25 阅读次数:4256次

利用存储过程对表中记录进行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)

--@Birthday=null

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/

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生