Unfortunately Sybase ASE does not have any native support for regex's, nor any out-of-the-box functions for stripping trailing zeros.
An obvious (?) first attempt might consist of a looping construct to strip off the trailing zeros, though it'd probably be easier to reverse()
the initial string, strip off leading zeros, then reverse()
to get back to the original value. Unfortunately this is not exactly efficient and would need to be encapsulated in a user-defined function (which introduces an additional performance hit each time it's invoked) in order to use it in a query.
The next idea would be to convert the zeros into something that can be (relatively) easily stripped off the end of the string, and it just so happens that ASE does provide the rtrim()
function for stripping trailing spaces. This idea would look something like:
- convert all zeros to spaces [
str_replace('string','0',' ')
]
- strip off trailing spaces [
rtrim('string')
]
- convert any remaining spaces back to zeros [
str_replace('string',' ','0')
]
** This obviously assumes the original string does not contain any spaces.
Here's an example:
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
If you need to use this code snippet quite often then you may want to consider wrapping it in a user-defined function, though keep in mind there will be a slight performance hit each time the function is called.