当VARCHAR包含Decimal时,您无法将其转换为INT - 为什么?

时间:2014-08-25 21:23:32

标签: tsql sql-server-2008-r2

我遇到了SQL代码试图将varchar转换/转换为int的问题。这是一个演示此问题的Transact SQL代码段。

declare     @code       varchar(100),
            @retCode    smallint,
            @intCode    int

select @retCode =   0, @code = '1.0000            '

select @intCode = convert(int, LTRIM(RTRIM(@code)))

您收到此错误:

  

Msg 245,Level 16,State 1,Line 9
  转换varchar值时转换失败' 1.0000'数据类型int。

显然,convert(和cast)无法直接将varchar十进制值转换为int

我必须这样做才能纠正它。

declare @code       varchar(100),
    @retCode    smallint,
    @intCode    decimal

select @retCode =   0, @code = '1.0000            '

select @intCode = convert(int, (convert(decimal, LTRIM(RTRIM(@code)))))
select @intCode

为什么上述修正工作 - varchar -> decimal -> int?为什么我无法从varchar进行直接转换,无论它在int的数值是多少?我想了解背后的原因。 (忽略上面的LTRIM / RTRIM ......它是不必要的)。

顺便说一下,我使用的是SQL Server 2008 R2。

非常感谢!

1 个答案:

答案 0 :(得分:1)

基本上,SQL Server不确定您正在尝试哪种类型的转换......

您可以通过直接指定变量来隐式转换为int:

SET @intcode = @Code -- This will Truncate the decimal portion of the number

或者,您可以使用TRY_CONVERT在SQL Server 2008中进行显式转换:

像这样:

select @intCode = convert( int, try_convert( decimal, @code )  )

无论哪种方式,你都没有进行字符串操作。

以下是Simple Talk上隐式与显式转换的一个很好的解释: here

干杯!