如何将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
我不能在表示层做,有人能帮我查询吗?
发布于 2018-01-04 07:53:16
不幸的是,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
如果您需要经常使用此代码片段,那么您可能需要考虑将其封装到用户定义的函数中,但请记住,每次调用该函数时,性能都会受到轻微的影响。
https://stackoverflow.com/questions/48095897
复制