T-SQL如何将varchar字母数字值与int值

时间:2016-07-13 11:21:16

标签: sql-server tsql

我正在尝试查询关系存储,以返回在数据包(broadcast.FirmwareVersionReported)中报告的值不同的对象与上次传递的值(device.firmwareid)相比较。

  • broadcast.FirmwareVersionReported的类型为varchar
  • 值示例为001

  • device.firmwareid的类型为int

  • 值示例为0001XX

测试

我尝试使用LEFT从列firmware.softwareid中移除最后两个字符来平衡比赛场地,并使用CAST将两者都更改为VARCHAR以进行比较。但很明显,这种做法并不正确。

select 
    LEFT(CAST(firmware.softwareid as VARCHAR),4) AS softwareid, 
    CAST(broadcast.[FirmwareVersionReported] as VARCHAR) 
from 
    device
inner join 
    broadcast on broadcast.deviceid = device.deviceid
inner join 
    firmware on firmware.firmwareid = device.firmwareid
where
    softwareid <> [FirmwareVersionReported]

结果

  

Msg 468,Level 16,State 9,Line 7
  无法在不等于操作的情况下解决“SQL_Latin1_General_CP1_CI_AS”和“Latin1_General_CI_AS”之间的排序规则冲突。

表格

广播

[DeviceId] [int],
[FirmwareVersionReported] [varchar](10),

固件

[FirmwareID] [int] IDENTITY(1,1),
[SoftwareID] [varchar](10),
[PacketSoftwareID] [varchar](10),

设备

[DeviceID] [int] IDENTITY(1,1),
[FirmwareID] [int],

问题

请寻求有关如何最好地解决此问题的建议。

2 个答案:

答案 0 :(得分:1)

不是转换为char,而是转换为int进行比较:

select 
    LEFT(CAST(firmware.softwareid as VARCHAR),4) AS softwareid, 
    CAST(broadcast.[FirmwareVersionReported] as VARCHAR) 
from device
    inner join broadcast on broadcast.deviceid = device.deviceid
    inner join firmware on firmware.firmwareid = device.firmwareid
WHERE floor(cast(softwareid as int)/100) <> cast([FirmwareVersionReported] as int)

答案 1 :(得分:0)

enter code here
select 
    LEFT(CAST(firmware.softwareid as VARCHAR),4) AS softwareid_mod, 
    CAST(broadcast.[FirmwareVersionReported] as VARCHAR) 
from device
    inner join broadcast on broadcast.deviceid = device.deviceid
    inner join firmware on firmware.firmwareid = device.firmwareid
WHERE LEFT(CAST(firmware.softwareid as VARCHAR),4) COLLATE DATABASE_DEFAULT <> [FirmwareVersionReported] COLLATE DATABASE_DEFAULT