【问题标题】:Presenting null values when field is null zip codes当字段为空邮政编码时显示空值
【发布时间】:2018-11-30 14:16:35
【问题描述】:

我正在努力解决这个问题。我正在处理邮政编码,但我正在尝试添加一个执行以下操作的整体功能:

如果您正在查看的字段为空白 (EMPTY),则返回/写入 (BLANK) 到新字段中。

目前正在发生以下情况:少于 5 个字符的所有内容都得到前导零,或者如果它为空白,则得到 00000

      update ImportStagingContact
         set zip = '0' + zip
       where len(zip) = 8
         and ImportLogID = @nImportLogID

      update ImportStagingContact
         set zip = replace(zip, '-', '')
       where len(zip) = 10
         and charindex('-', zip) > 0
         and ImportLogID = @nImportLogID

      update ImportStagingContact
         set zip = right('00000' + zip, 5)
       where len(zip) < 5
         and ImportLogID = @nImportLogID

      update ImportStagingContact
         set zip = left(zip, 5)
       where len(zip) = 9
         and ImportLogID = @nImportLogID

【问题讨论】:

  • 您使用的是什么类型的 SQL? MS、MY 等?您也可以使用案例陈述并进行一次更新(可能因您的技术而异)。这会做你需要的。当您进行上述更新时,如果第一次更新运行,那么第二次更新仍然可以在相同的记录上再次运行,如果您使用不会发生的 case 语句
  • 我在我的回答中添加了一个更新,要求澄清
  • 样本数据和期望/实际结果真的很有帮助——连同数据库标签。

标签: sql zipcode


【解决方案1】:

更新:

您想要的结果是什么? 5 位数还是 9 位数的邮编?让我知道,我可以更新以更好地工作

更仔细地查看您的逻辑,这可能无法正常工作,具体取决于您想要的结果。

第一个更新是将 zip 设置为 9 位数,但底部 2 将其限制为看起来像的 5 位数。那么如果使用case语句会得到不一致的结果吗?

您可能需要对 5 位或 9 位大小写进行 2 次更新,并需要进行 1 次更新以清理数据(删除 -)(或者可以在其他情况下合并)。

根据您的技术,这应该在 MSSQL 中工作。您可以更改 case 语句的顺序,以便您首先要运行的语句高于其他语句。如果不是MSSQL,逻辑应该是一样的,bug语法可能不同。

UPDATE ImportStagingContact
SET zip = 
    CASE
        -- to set to blank, maybe set to null if that is desired vs blank 
        WHEN len(ISNULL(zip, '') = 0 then '' 
        WHEN len(zip) = 8 THEN '0' + zip
        WHEN len(zip) = 10 and charindex('-', zip) > 0 THEN replace(zip, '-', '')
        WHEN len(zip) < 5 THEN right('00000' + zip, 5) 
        WHEN len(zip) = 9 THEN left(zip, 5)
    END
where ImportLogID = @nImportLogID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多