在SQL中将nvarchar转换为整数

时间:2015-05-22 14:55:20

标签: sql sql-server

我有一个表格,其中版本值是nvarchar而不是整数,因此当我使用大于语句时,它不会撤回正确的数据

我正在尝试将版本转换为整数但收到错误,请帮助

Declare @dversion   int;

set @dversion = (select convert(int, displayversion) from Inv_AddRemoveProgram where DisplayName like 'Symantec Enterprise Vault%')

select distinct v1.name, v1.[user], t1.displayname, @dversion from vComputer v1

inner join Inv_AddRemoveProgram t1
on v1.Guid = t1._ResourceGuid

where t1.DisplayName like 'Symantec Enterprise Vault%'

and @dversion > '10.0.17573'

收到错误:消息245,级别16,状态1,行3 转换nvarchar值时转换失败' 10.0.17573'数据类型int。

我还尝试编写两个简单的查询来转换该表中的版本值,该值也没有用

select displayname, CONVERT(INT, displayversion) from Inv_AddRemoveProgram

Error:  Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '3.1.05160' to data type int.

select displayname, CAST(displayversion AS INT) from Inv_AddRemoveProgram

Error:  Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '3.1.05160' to data type int.

3 个答案:

答案 0 :(得分:0)

看起来您的问题可能是您正在尝试将float转换为int。或者,实际上,我不确定是什么类型的数字' 3.1.05160'可能。可能甚至不是一个带有两位小数的浮点数。

如果你想在这样的领域进行安排,我认为你需要将这个数字分成3个部分,然后将它们分成数字,然后按顺序排列?

答案 1 :(得分:0)

你需要int in clausule。试试这个:

and @dversion > CAST(replace('10.0.17573', '.', '') as int)

答案 2 :(得分:0)

试试这个:

DECLARE @t TABLE ( v NVARCHAR(20) )
INSERT  INTO @t
VALUES  ( '10.0.17573' ),
        ( '10.1.17573' ),
        ( '10.0.1753' ),
        ( '12.3.17573' ),
        ( '11.0.17573' ),
        ( '9.0.17573' ),
        ( '9.20.17573' )

SELECT  *
FROM    @t
WHERE   CAST(PARSENAME(v, 3) AS INT) > CAST(PARSENAME('10.0.17573', 3) AS INT)
        OR ( CAST(PARSENAME(v, 3) AS INT) >= CAST(PARSENAME('10.0.17573', 3) AS INT)
             AND CAST(PARSENAME(v, 2) AS INT) > CAST(PARSENAME('10.0.17573', 2) AS INT))
        OR ( CAST(PARSENAME(v, 3) AS INT) >= CAST(PARSENAME('10.0.17573', 3) AS INT)
             AND CAST(PARSENAME(v, 2) AS INT) >= CAST(PARSENAME('10.0.17573',2) AS INT)
             AND CAST(PARSENAME(v, 1) AS INT) > CAST(PARSENAME('10.0.17573',1) AS INT))

输出:

v
10.0.17573
10.1.17573
12.3.17573
11.0.17573