试图摆脱查询中不需要的记录

时间:2011-07-01 00:29:26

标签: tsql

我有以下查询

Select * from Common.dbo.Zip4Lookup where 
zipcode='76033' and 
StreetName='PO BOX' and 
'704' between AddressLow and AddressHigh and 
(OddEven='B' or OddEven = 'E')

AddressLow和AddressHigh列是varchar(10)字段。

返回的记录是

AddressLow   AddressHigh
------------ ------------
1            79
701          711

第二个是所需的记录如何摆脱第一条记录。

2 个答案:

答案 0 :(得分:2)

问题是SQL使用字符串比较而不是数字比较。这是因为AddressLow / High是varchar而不是int

只要AddressLow / High包含数字,这应该有效:

Select * from Common.dbo.Zip4Lookup where 
   zipcode='76033' and 
   StreetName='PO BOX' and 
   704 between 
       CAST(AddressLow as INT) and 
       CAST(AddressHigh as INT) and 
   (OddEven='B' or OddEven = 'E')

答案 1 :(得分:1)

问题是您的条件适合7开头的79中的第一条记录,因为它是字符串值。最简单的方法是恕我直言将数据类型更改为某个数字类型。