SQL Server - 从表中删除不必要的零

时间:2013-02-25 17:15:45

标签: sql sql-server-2008

我想在显示此表时删除不必要的零

Produit | Prix
---------------
   A    | 1000.65400
   B    | 1200.654000
   C    | 2540.6540000
   D    | 1000.25000
   E    | 224000.6540000000

我想得到这个结果:

Produit | Prix
---------------
   A    | 1000.654
   B    | 1200.654
   C    | 2540.654
   D    | 1000.25
   E    | 224000.654

任何帮助都将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:0)

修剪前导和尾随不需要的0:

UPDATE yourTable
SET Prix = CASE
  WHEN Prix LIKE '%.%[1-9]%' THEN -- has a non-0 after the decimal point
    REPLACE(RTRIM(LTRIM(REPLACE(Prix, '0', ' '))), ' ', '0')
  WHEN Prix LIKE '%.%' THEN -- only 0's after the decimal point, remove point
    REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(Prix, '0', ' '))), ' ', '0'), '.', '')
  ELSE -- has no decimal point, only trim leading 0's
    REPLACE(LTRIM(REPLACE(Prix, '0', ' ')), ' ', '0')
  END

如果您只想修剪尾随:

UPDATE yourTable
SET Prix = CASE
  WHEN Prix LIKE '%.%[1-9]%' THEN -- has a non-0 after the decimal point
    REPLACE(RTRIM(LTRIM(REPLACE(Prix, '0', ' '))), ' ', '0')
  ELSE -- only 0's after the decimal point, remove point
    REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(Prix, '0', ' '))), ' ', '0'), '.', '')
  END
WHERE Prix LIKE '%.%' -- make sure it's decimal

上面用空格替换所有0,使用内置修剪函数修剪空格,然后再用0替换空格。