2013-02-25 44 views
0

刪除不必要的零我想刪除不必要的零顯示該表SQL服務器 - 從表

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 

任何幫助將升值。 謝謝

+0

爲什麼你需要去3位小數? – 2013-02-25 17:17:46

+0

'Prix'是'VARCHAR'字段嗎?如果是這樣,爲什麼? – Dukeling 2013-02-25 17:21:09

+3

請不要要求SQL Server執行此操作 - 在表示層中對其所屬的位置進行美化。 – 2013-02-25 17:21:38

回答

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 s的空間,使用內置的修剪功能修剪空格,然後再用0 s替換空格。

+0

UPDATE yourTable SET大獎賽= CASE WHEN大獎賽LIKE '%。%' THEN REPLACE(RTRIM( LTRIM(REPLACE(Prix,'0',''))),'','0') ELSE - 沒有小數點,只修整前導0的 REPLACE(LTRIM(REPLACE(Prix,'0',' ')),'','0') END此解決方案正常工作,但它會生成一個錯誤,如果我們有23651.0000 - 它給 - > 23651,而不是23651 – user1805523 2013-02-26 08:10:48

+1

@ user1805523編輯。現在應該工作。 – Dukeling 2013-02-26 08:36:57

+0

謝謝soooo多 – user1805523 2013-02-26 12:33:25