将数字(18,2)转换为varchar

时间:2014-04-16 13:05:51

标签: sql sql-server tsql

我有下表:

DECLARE @T TABLE(
    Val NUMERIC(18,2)

具有以下值:

INSERT INTO @T SELECT 3.01
INSERT INTO @T SELECT 30
INSERT INTO @T SELECT 2.00
INSERT INTO @T SELECT 2.1

当我运行此命令时:

SELECT * FROM @T

我明白了:

3.01
30.00
2.00
2.10

我想得到的是:

3.01
30
2
2.1

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

完全是hackish,但是一个简单的解决方案。但是,它不会出现舍入错误。

DECLARE @T TABLE(
    Val NUMERIC(18,2)
)

INSERT INTO @T SELECT 3.01
INSERT INTO @T SELECT 30.00
INSERT INTO @T SELECT 2.0
INSERT INTO @T SELECT 2.10
INSERT INTO @T SELECT 2.20
INSERT INTO @T SELECT 2.30
INSERT INTO @T SELECT 2.40
INSERT INTO @T SELECT 2.50
INSERT INTO @T SELECT 2.60
INSERT INTO @T SELECT 2.70
INSERT INTO @T SELECT 2.80
INSERT INTO @T SELECT 2.90

select
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
        convert(varchar,Val)
    ,'.00','')
    ,'.10','.1')
    ,'.20','.2')
    ,'.30','.3')
    ,'.40','.4')
    ,'.50','.5')
    ,'.60','.6')
    ,'.70','.7')
    ,'.80','.8')
    ,'.90','.9')
from @T

答案 1 :(得分:0)

为什么不使用实数类型。以下是两种方式。

DECLARE @T TABLE(
    Val real
)

INSERT INTO @T SELECT 3.01
INSERT INTO @T SELECT 30
INSERT INTO @T SELECT 2.00
INSERT INTO @T SELECT 2.1

SELECT Val FROM @T

OR

DECLARE @T TABLE(
    Val NUMERIC(18,2)
)

INSERT INTO @T SELECT 3.01
INSERT INTO @T SELECT 30
INSERT INTO @T SELECT 2.00
INSERT INTO @T SELECT 2.1

SELECT cast(Val as real) FROM @T

答案 2 :(得分:-1)

SELECT Cast(Val AS Float) from @T