sql - 使用 case 语句更新字段

标签 sql case

对于查询结果中的以下人员,UniqueIDSuffix值应以前导0填充,字符长度= 6。UniqueIDSuffix修改后,UniqueID值应通过UniqueIDPrefix + UniqueIDSuffix = UniqueID更新为字符长度= 9

select * from cph..cppat (nolock) where 
UniqueIDPrefix is not null and 
UniqueIDPrefix <> 'VIS' and len(UniqueIDSuffix) < 6

按 UniqueIDPrefix asc 排序

我的声明是:

SET UniqueIDsuffix  =
        (CASE
           WHEN UniqueIDsuffix = 3 THEN '000' + UniqueIDsuffix  ELSE
           When UniqueIDsuffix = 4 THEN '00' + UniqueIDsuffix ELSE
           WHEN UniqueIDsuffix = 5 Then '0' + UniqueIDsuffix ELSE
           WHEN UniqueIDsuffix = 6 THEN UniqueIDsuffix ELSE
           )
where UniqueIDPrefix is not null and UniqueIDPrefix <> 'VIS' 
and len(UniqueIDSuffix) < 6

最佳答案

您缺少更新语句。 。 。并且您有无关的 else 语句。 。 。并且您在比较中缺少 len() 函数:

update cph..cppat
    SET UniqueIDsuffix  =
            (CASE WHEN len(UniqueIDsuffix) = 3 THEN '000' + UniqueIDsuffix 
                  When len(UniqueIDsuffix) = 4 THEN '00' + UniqueIDsuffix 
                  WHEN len(UniqueIDsuffix) = 5 Then '0' + UniqueIDsuffix 
                  WHEN len(UniqueIDsuffix) = 6 THEN UniqueIDsuffix 
            )
    where UniqueIDPrefix is not null and UniqueIDPrefix <> 'VIS' and len(UniqueIDSuffix) < 6

顺便说一句,您可以更简单地表达为:

update cph..cppat
    SET UniqueIDsuffix  = right('0000000'+UniqueIDSuffix, 6)
    where UniqueIDPrefix is not null and UniqueIDPrefix <> 'VIS' and len(UniqueIDSuffix) < 6

关于sql - 使用 case 语句更新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14142543/

相关文章:

sql - 获取所有先前值的总和? - 到目前为止总共?

case - CRM 2011 - 使用案例表单上的联系数据

sql - 在 Oracle SQL 中 Case 语句的 When 部分中使用别名

MySQL JOIN 查询 - 右表中的一行对应左表中的每一行,并优先考虑所包含的数据

MySQL:选择每个聚合组中的最后一行

mysql - MySQL 中何时使用单引号、双引号和反引号

c - if else 语句没有给出预期的答案

mysql - 如何查询和重新组织当前 MySQL 数据库中的数据?

Mysql查询问题,列不为空时插入行的情况

java - 如何在 HQL 中使用 sql case 子句?