使用case语句更新字段

时间:2013-01-03 16:03:19

标签: sql case

对于下面的查询结果中的People,对于字符长度= 6,应使用前导0填充UniqueIDSuffix值。在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

1 个答案:

答案 0 :(得分:3)

您缺少更新语句。 。 。而且你有无关的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