【问题标题】:Convert the Numeric data type to varchar without trailing Zeros in sybase在 sybase 中将 Numeric 数据类型转换为无尾随零的 varchar
【发布时间】:2018-01-04 13:00:07
【问题描述】:

如何将 SQL 数据类型 Numerci(15,2) 转换为字符串(varchar 数据类型)而不在 sybase 中添加尾随零。

示例-在 abc 列中存在以下值-

0.025
0.02
NULL
0.025589
5.289

关于运行查询-

select STR(column,10,4) from table --- produces the results 0.025,0.0200
select CAST(column as CHAR(5)) from table -- produces the results as 0.0250 etc

我在表现层做不到 有人可以帮忙查询吗?

【问题讨论】:

  • ANSI SQL:trim(trailing '0' from cast(column as varchar(20)))
  • 如果@jarlh 的上述评论不起作用,那么我认为您需要某种正则表达式支持才能做到这一点。或者,您可以在表示层中处理它。
  • @Tim 谢谢,但没用
  • 使用正则表达式有时会过度影响 sql 查询的性能
  • @SurjitSD 您还打算如何从十进制数的末尾去除任意数量的零?我不认为 Sybase 的基本字符串函数可以处理这个问题。

标签: sql sybase-ase15


【解决方案1】:

不幸的是,Sybase ASE 没有对正则表达式的任何本机支持,也没有任何用于去除尾随零的现成函数。

一个明显的(?)第一次尝试可能包括一个循环结构来去除尾随零,尽管reverse() 初始字符串可能更容易,去除前导零,然后reverse() 回来到原来的值。不幸的是,这并不完全有效,并且需要封装在用户定义的函数中(每次调用都会带来额外的性能损失)才能在查询中使用它。

下一个想法是将零转换为可以(相对)容易地从字符串末尾剥离的东西,而 ASE 确实提供了 rtrim() 函数来剥离尾随空格。这个想法看起来像:

  • 将所有零转换为空格 [str_replace('string','0',' ')]
  • 去掉尾随空格 [rtrim('string')]
  • 将所有剩余的空格转换回零 [str_replace('string',' ','0')]

** 这显然假设原始字符串不包含任何空格。

这是一个例子:

declare @mystring varchar(100)

select  @mystring = '0.025000'

-- here's a breakdown of each step in the process ...

select ':'+                               @mystring                    + ':' union all
select ':'+                   str_replace(@mystring,'0',' ')           + ':' union all
select ':'+             rtrim(str_replace(@mystring,'0',' '))          + ':' union all
select ':'+ str_replace(rtrim(str_replace(@mystring,'0',' ')),' ','0') + ':'

-- and the final solution sans the visual end markers (:)

select str_replace(rtrim(str_replace(@mystring,'0',' ')),' ','0')
go

 ----------
 :0.025000:
 : . 25   :
 : . 25:
 :0.025:

 --------
 0.025

如果您需要经常使用此代码 sn-p,那么您可能需要考虑将其包装在用户定义的函数中,但请记住,每次调用该函数时都会对性能造成轻微影响。

【讨论】:

    【解决方案2】:

    可以使用以下方法 - 1)它使用替换功能

    select COLUMN,str_replace(rtrim(str_replace(
           str_replace(rtrim(str_replace(cast(COLUMN as varchar(15)), '0', ' ')), ' ', '0')
           , '.', ' ')), ' ', '.')
    from TABLE
    

    输出 -

    0.025
    2


    0.025
    2

    2) 使用正则表达式-

    select COLUMN ,str(COLUMN ,10,3),  
        reverse(substring( reverse(str(COLUMN ,10,3)), patindex('%[^0]%',reverse(str(COLUMN ,10,3))), 10)) 
    from TABLE
    

    输出 -

    0.025
    2


    0.025
    2.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多