【问题标题】:How to ignore Null values at the end of a string in Oracle?如何在 Oracle 中忽略字符串末尾的 Null 值?
【发布时间】:2019-04-15 12:50:20
【问题描述】:

我有一个数据类型为 VARCHAR2(18) 的列 nse_credit_rating。 它包含189.00-250.00 形式的值。 但有些记录在字符串末尾有空值,即即使与我相关的数据长度为 13 (189.00-250.00) 但 length(nse_credit_rating) 返回 17 作为输出,即末尾有 4 个空值。

当我必须在此列上使用 to_number 时出现主要问题,它返回“ORA-1722 无效数字”,因为它包含 null。

有没有办法在 NULL 值出现之前获取子字符串? 我什至拿了dump(nse_credit_rating)的输出。

SELECT dump(nse_credit_rating),nse_symbol 
FROM nse_security_master 
where nse_series='EQ'
  and nse_symbol like 'ARVIND' 
  and nse_series='EQ'

输出:

Typ=1 Len=17: 51,54,55,46,48,48,45,52,52,56,46,53,48,0,0,0,0

这里 0 是 NULL 的 ascii。

SELECT (nse_credit_rating),nse_symbol 
FROM nse_security_master 
where nse_series='EQ'
and nse_symbol like 'ARVIND' 
and nse_series='EQ'

输出:

367.00-448.50

我尝试使用ascii(substr(nse_credit_rating,-1,1)),但这仅在我知道最后只有一个字符为 Null 时才有效。但可能有任意数量的字符为 NULL。

【问题讨论】:

    标签: sql oracle nul


    【解决方案1】:

    使用rtrim() 删除字符串末尾的字符:

    SELECT rtrim(nse_credit_rating, chr(0)) as nse_credit_rating
          ,nse_symbol 
    FROM nse_security_master 
    where nse_series='EQ'
    and nse_symbol like 'ARVIND' 
    and nse_series='EQ'
    

    这在 Oracle SQL 文档中有介绍。 Find out more。 Oracle 还支持标准的 SQL trim() 函数,但稍微有点冗长:

    SELECT trim(trailing chr(0) from nse_credit_rating) as nse_credit_rating
           , nse_symbol 
    FROM nse_security_master 
    where nse_series='EQ'
    and nse_symbol like 'ARVIND' 
    and nse_series='EQ'
    

    你能告诉我 chr(0) 在这里做什么吗?

    chr() 是一个将 ASCII 数字转换为字符的函数。所以chr(0) 给了我们 ASCII null。

    【讨论】:

    • 谢谢,这是返回正确的长度。你能告诉我 chr(0) 在这里做什么吗?
    【解决方案2】:

    简单的方法是使用修剪功能。详细信息在下面的链接 https://docs.oracle.com/javadb/10.8.3.0/ref/rreftrimfunc.html

    或直接使用rtrim

    【讨论】:

    • 这是一个常用功能..这里的目的是指出正确的方向..但为这个特定案例添加了另一个链接。
    • 只链接到其他地方的答案不是好的答案。一个好的答案是独立的,不需要链接。 (尽管链接是补充答案或提供更多信息的好方法。)
    • 直接使用 rtrim 并不能解决问题,但是正如@APC 提到的那样 rtrim(nse_credit_rating,chr(0)) 得到了结果。
    • 我明白你的观点,即有一个独立的答案并同意它。但我普遍信奉“授人以渔的方法”。探索更多,尝试并从中学习一些额外的东西。这只是一个不同的观点。 :)
    • " 只是观点不同而已。" 其实不然。 StackOverflow 有关于什么是好答案和什么不是好答案的成熟惯例。仅链接的答案绝对不是好答案。请阅读this Meta response to understand why
    猜你喜欢
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多