SQL Server - 删除前导和尾随零

时间:2016-05-03 13:31:31

标签: sql-server tsql sql-server-2012

我需要从数据集中删除前导零和尾随零:

WITH

data as (
    select 0.10 ITEM
    union all
    select -1.00
    union all
    select 0.20
    union all
    select 2.00
    union all
    select 508000015.00
)

结果类似于:

ITEM
.1
-1
.2
2
508000015

是否有更简洁或更有效的方法

SELECT  case
          # if item isn't an integer, trim 0 from left and right 
          when item % 1 = item then REPLACE(RTRIM(LTRIM(REPLACE(item,'0',' '))),' ','0') 
          else cast(cast(item as int) as varchar) 
        end VALUE
FROM    data

4 个答案:

答案 0 :(得分:1)

这样的事情也可以起作用:

WITH
data as (
    select 0.10 ITEM
    union all
    select -1.00
    union all
    select 0.20
    union all
    select 2.00
    union all
    select 508000015.00
)
SELECT  *
FROM    data as d
CROSS
APPLY   (SELECT 
                SUBSTRING(CAST(ITEM AS varchar(32)), PATINDEX('0%', CAST(ITEM AS VARCHAR(32))) + 1, LEN(ITEM))) AS f (lead0) -- remove leading 0
CROSS
APPLY   (SELECT 
                SUBSTRING(f.lead0, 1, CASE 
                                        WHEN RIGHT(f.lead0, 2) = '00' THEN LEN(f.lead0) - 3 -- remove decimal point as well
                                        WHEN RIGHT(f.lead0, 1) = '0' THEN LEN(f.lead0) - 1 
                                        ELSE LEN(f.lead0) 
                                    END)) AS s (end0);

答案 1 :(得分:0)

尝试类似......

WITH data as (
    select 0.10 ITEM
    union all
    select -1.00
    union all
    select 0.20
    union all
    select 2.00
    union all
    select 508000015.00
)
Select CASE WHEN RIGHT( REPLACE(RTRIM(LTRIM(REPLACE(ITEM,'0',' '))),' ','0'), 1) = '.'
           THEN REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(ITEM,'0',' '))),' ','0'),'.','')
           ELSE REPLACE(RTRIM(LTRIM(REPLACE(ITEM,'0',' '))),' ','0') END
from data

答案 2 :(得分:0)

如果要将数据存储在numeric(12,2)列中,则无关紧要。 SQL Server将始终显示带有2位小数的内容。

SELECT
    CAST(1.0 AS NUMERIC(12, 2))     AS [NoDp],
    CAST(1.0 AS NUMERIC(12, 2))     AS [1Dp],
    CAST(1.00 AS NUMERIC(12, 2))    AS [2Dp],
    CAST(1.000 AS NUMERIC(12, 2))   AS [3Dp]
;

返回

NoDp    1Dp     2Dp     3Dp
1.00    1.00    1.00    1.00

如果您对格式化输出感兴趣,最好在表示层中完成。

答案 3 :(得分:0)

我认为这可能更简单。抱怨懒惰,但我想你会明白这一点。

WITH data as (
 select 0.10 ITEM
 union all
 select -1.00
 union all
 select 0.20
 union all
 Select 2.00
 union all
 select 508000015.00
 union all
 select 508015
 union all
 select 50815)

set1 as (Select
case when LEN(item) > 6 then cast(cast(item as numeric) as varchar)
else cast(cast(item as float) as varchar)
end item
from data)

select
case
    when item like '0.%' then RIGHT(item,len(item)-1) else item
end As item
from set1