【问题标题】:REPLACE not doing what I need in SQL替换不在 SQL 中做我需要的事情
【发布时间】:2023-03-19 04:45:01
【问题描述】:

我有一个查询从表中提取数据。在一个特定的领域,有几种情况是零,但我需要四位数的位置号码。这是我遇到问题的地方。我有

SELECT REPLACE(locationNbr, '0', '1035') AS LOCATION...

两个问题-

  1. 将表放在一起的人将所有字段设为 VARCHAR,因此使用了单引号。
  2. 在已经存在数字 1035 的情况下,我得到 1103535 作为位置编号,因为它正在替换 1035 中间的零。

如果 locationNbr 字段不是零(作为 VARCHAR),如何选择 locationNbr 字段并保持不变,但如果它为零,请将其更改为 1035?有没有办法在 REPLACE 中以某种方式使用 TO_NUMBER?

【问题讨论】:

    标签: sql oracle replace


    【解决方案1】:

    不要使用replace()。使用case

    (case when locationNbr = '0' then '1035' else locationNbr end)
    

    【讨论】:

      【解决方案2】:
      SELECT CASE WHEN locationNbr='0' THEN '1035' ELSE locationNbr END AS LOCATION...
      

      REPLACE( string, string_to_replace , replacement_string )

      REPLACEstring 中查找string_to_replace 并将其替换为replacent_string。这就是您得到不良行为的原因 - 您使用了错误的功能。

      CASE WHEN condition THEN result1 ELSE result2 END CASE 检查condition,如果为真则返回result1,否则返回result2。这是一个简单的例子,你可以编写一个带有多个条件检查的 case 语句。

      【讨论】:

        【解决方案3】:

        您可以在 Oracle 中使用长度:

        select case when length(loacation) = 1 then REPLACE(loacation, '0', '1035') else loacation end as location
        from location_test;
        

        【讨论】:

          猜你喜欢
          • 2014-04-23
          • 1970-01-01
          • 1970-01-01
          • 2013-03-27
          • 1970-01-01
          • 2017-08-01
          • 2023-03-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多