SQL与varchar列之间存在问题

时间:2013-11-28 13:33:31

标签: tsql varchar between

在使用varchar列进行比较时,我遇到了使用Between的问题。当我运行时:

SELECT DISTINCT diag_1, Diag_2, Diag_Admit
FROM  Data_Exchange c

WHERE (Diag_1  BETWEEN '29600' and '29606' )

OR (Diag_2 BETWEEN '29600' and '29606')

OR (Diag_Admit between  '29600' and '29606')
------
OR (Diag_1 between '29640' and  '29680')

OR (Diag_2 between '29640' and '29680')

OR (Diag_Admit between '29640' and '29680')

我在结果中显示以下内容:     2967

我不希望这样。如果它没有5位数,则不应显示在结果中。

我该如何解决这个问题?

感谢。

2 个答案:

答案 0 :(得分:1)

如果您只想将要检查的字符串长度限制为5个字符,则为每列添加where子句:

--Untested(sorry)
SELECT DISTINCT diag_1, Diag_2, Diag_Admit
FROM  Data_Exchange c
WHERE LEN(Diag_1)=5 
AND LEN(Diag_2)=5
AND LEN(Diag_Admit)=5
AND (   Diag_1  BETWEEN '29600' and '29606'
     OR Diag_2 BETWEEN '29600' and '29606'
     OR Diag_Admit between  '29600' and '29606'
     OR Diag_1 between '29640' and  '29680'
     OR Diag_2 between '29640' and '29680'
     OR Diag_Admit between '29640' and '29680')

<强>然而 查看varchar列中的所有这些数字让我担心其他事情可能正在发生......

当列是alpha类型时,它按字母顺序排序,因此'2967'应介于'29640'和'29680'之间。

理想情况下,如果列只包含数字,则应将数据类型转换为适当的数字类型,但如果不可行,则此处为解决方法。

按字母顺序排序列表1,2,11,12,13将显示为1,11,12,13,2,如以下SQL所示。

--Test data.
DECLARE @alphaSort AS TABLE(col1 VARCHAR(2))
INSERT INTO @alphaSort VALUES('1')
INSERT INTO @alphaSort VALUES('2')
INSERT INTO @alphaSort VALUES('11')
INSERT INTO @alphaSort VALUES('12')
INSERT INTO @alphaSort VALUES('13')
SELECT col1 FROM @alphaSort ORDER BY col1

--Results:
col1
1
11
12
13
2

如果您希望BETWEEN语句可预测地用于数字,则必须将列转换为数字类型:

SELECT col1 FROM @alphaSort ORDER BY CONVERT(INT,col1)
--Results
col1
1
2
11
12
13

如果列中包含混合数据,则需要使用ISNUMERIC函数来避免以下错误:

--New test data.
DECLARE @alphaSort AS TABLE(col1 VARCHAR(2))
INSERT INTO @alphaSort VALUES('1')
INSERT INTO @alphaSort VALUES('2')
INSERT INTO @alphaSort VALUES('11')
INSERT INTO @alphaSort VALUES('12')
INSERT INTO @alphaSort VALUES('13')
INSERT INTO @alphaSort VALUES('a')

--WITHOUT ISNUMERIC
SELECT col1 FROM @alphaSort ORDER BY CONVERT(INT,col1)

--Results
Msg 245, Level 16, State 1, Line xx
Conversion failed when converting the nvarchar value 'a' to data type int.

--WITH ISNUMERIC
SELECT col1 FROM @alphaSort WHERE ISNUMERIC(col1) = 1 ORDER BY CONVERT(INT,col1)

--Results
col1
1
2
11
12
13

答案 1 :(得分:0)

如果您要做的只是测试列的大小是否更大,那么您可以这样做

select * from Data_Exchange 
where len(Diag_1) >4 

如果不是,我认为你需要在where子句周围添加另一组()。我认为它变得混乱

SELECT DISTINCT diag_1, Diag_2, Diag_Admit
FROM  Data_Exchange c
WHERE ((Diag_1  BETWEEN '29600' and '29606' )
   OR (Diag_2 BETWEEN '29600' and '29606')
   OR (Diag_Admit between  '29600' and '29606')
   OR (Diag_1 between '29640' and  '29680')
   OR (Diag_2 between '29640' and '29680')
   OR (Diag_Admit between '29640' and '29680'))