无法将数据类型varchar转换为数字

时间:2016-12-02 05:47:15

标签: sql-server sql-server-2008

我有下表:

id  amount
12  974
11  929
9   837,5
4   606,5

我已经花了datatype as varchar(100)。现在,当我试图转换为十进制时,那时它给我转换错误。

我写了以下查询:

select id,cast(amount as decimal(10,2)) as amount from table order by amount desc

使用上述查询我收到错误:Error converting data type varchar to numeric.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

     create function [dbo].[udf_splitstring] (@tokens    varchar(max),
                                             @delimiter varchar(5))
    returns @split table (
      token varchar(200) not null )
    as
      begin
          declare @list xml

          select @list = cast('<a>'
                              + replace(@tokens, @delimiter, '</a><a>')
                              + '</a>' as xml)

          insert into @split
                      (token)
          select ltrim(t.value('.', 'varchar(200)')) as data
          from   @list.nodes('/a') as x(t)

          return
      end


 CREATE TABLE Table5
        ([id] int, [amount] varchar(100))

        INSERT INTO Table5
            ([id], [amount])
        VALUES
        (12,'974'),
        (11,'929'),
        (9 ,'837,5'),
        (4 ,'606,5')

        select id,cast(token as decimal(10,2)) as amount from Table5 
        cross apply (select token from udf_splitstring([amount], ',') )a

    id  amount
    12  974.00
    11  929.00
    9   837.00
    9   5.00
    4   606.00
    4   5.00

或 2)

    select id,amount,cast(replace (amount,',','.' )as decimal(10,2)) as amount1  from Table5

id  amount  amount1
12  974 974.00
11  929 929.00
9   837,5   837.50
4   606,5   606.50

3)

SELECT *,
    TRY_PARSE( [amount] AS NUMERIC(10,2) USING 'El-GR' ) x
FROM Table5

答案 1 :(得分:0)

如果字符串包含逗号,则无法直接转换为十进制, 您可以将字符串转换为Money类型

    ;WITH t(id,amount)AS(
       SELECT 12,'974' UNION
       SELECT 11,'929' UNION
       SELECT 9,'837,5.123' UNION
       SELECT 4,'606,5'
       )
    SELECT id,CONVERT(MONEY,t.amount) FROM t WHERE ISNUMERIC(t.amount)=1
id          
----------- ---------------------
4           6065.00
9           8375.123
11          929.00
12          974.00