Sql server 未在查询中使用嵌套 case 语句更新记录

Posted

技术标签:

【中文标题】Sql server 未在查询中使用嵌套 case 语句更新记录【英文标题】:Sql server not updating records with nested case statement in a query 【发布时间】:2021-01-05 10:27:50 【问题描述】:

我使用的是 sql server 2012,这是我的查询:

update  tablename set column1=case
when  column2 is null or column2=''  then '1st' 

when  column3 like 'Information%'  and 
(DATEDIFF(YEAR,convert(datetime,column6,103),getdate())) not IN (18,19,20,21)  then '2nd a' 


when  column3 not like 'Information%' and (DATEDIFF(YEAR,convert(datetime,column6,103),getdate())) 
not IN (21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40) then '2nd b'  

when column4 not like '%[^0-9]%' and 
CAST(replace(replace(column5,',',''),'','0') as bigint)
< 10*CAST(CAST((replace(ISNULL(REPLACE(column5,'','0'),'0'),',','')) as float) as bigint)/100  and column12='1' 
then '3rd a'  


when column4 not like '%[^0-9]%' and 
CAST(replace(replace(column5,',',''),'','0') as bigint)
< 20*CAST(CAST((replace(ISNULL(REPLACE(column5,'','0'),'0'),',','')) as float) as bigint)/100  and column12='2' or column12='3' 
then '3rd b'  


when  UPPER(column20)='YES'  or column20='Yes' or column20='Unknown' then '4th' 


when   column15<>'' and column15  not in (select  column2 from  table2) and 
CAST((replace(ISNULL(column15,'0'),',','')) as int) <1000000 
then '5th' 
else  null
end
,  

column2=
case
when    column1='1st'     then  'Rejected Reason'
when    column1='2nd a'   then  'Rejected Reason'
when    column1='2nd b'   then  'Rejected Reason'
when    column1='3rd a'   then  'Rejected Reason'
when    column1='3rd b'   then  'Rejected Reason'
when    column1='4th'     then  'Rejected Reason'
when    column1='5th'     then  'Rejected Reason'
else null end , column10=1  where column11=null

它不是更新我的表格只是结果

(0 row(s) affected)

即使我尝试了单个查询,也无法配置问题

update  tablename set column1=case
when  column2 is null or column2=''  then '1st' 
else  null
end
where column11=null

我做错了什么吗? 或任何其他方式来达到我想要的结果?

【问题讨论】:

当您在查询前面使用正确的比较 (column2 is null) 时,为什么还要使用 column11=null 【参考方案1】:
 where column11=null

必须写 WHERE Column11 IS NULL

【讨论】:

以上是关于Sql server 未在查询中使用嵌套 case 语句更新记录的主要内容,如果未能解决你的问题,请参考以下文章

在 SQL Server 中执行嵌套 case 语句逻辑的最佳方法

SQL查询语句SELECT中带有case when嵌套子查询判断的问题

在 SQL Server 中结合 dbplyr 和 case_when

SQL Server 之 子查询与嵌套查询

嵌套 CASE 的 T-SQL 替代方案以获得更好的性能?

SQL Server的高级知识