获取仅为数字的记录

时间:2011-12-20 20:55:52

标签: sql-server sql-server-2005

我正在运行此查询。在大多数情况下它工作正常,但有一些记录有非数字部分,这会引起问题。我需要能够只选择整数的记录。

select distinct SUBSTRING(PAPROJNUMBER, 1, 5) AS STUDY_NUMBER
        FROM         dbo.PA01201 AS PA01201_1
        where PAPROJNUMBER>'0'

例如,结果列表的一部分如下所示:

68145
68146
68147
7762A
99999
LABOR

我想要除7762A和LABOR之外的所有人。如何修改where子句以有效实现?

3 个答案:

答案 0 :(得分:6)

将“.0e0”添加到子字符串将确保ISNUMERIC仅返回有效的整数。

select distinct SUBSTRING(PAPROJNUMBER, 1, 5) AS STUDY_NUMBER
    FROM dbo.PA01201 AS PA01201_1
    where PAPROJNUMBER>'0'
        AND ISNUMERIC(SUBSTRING(PAPROJNUMBER, 1, 5) + '.0e0') = 1

答案 1 :(得分:2)

您可以执行以下操作

SELECT
  SUBSTRING(PAPROJNUMBER, 1, 5) AS STUDY_NUMBER
FROM dbo.PA01201
WHERE SUBSTRING(PAPROJNUMBER, 1, 5) LIKE '[0-9][0-9][0-9][0-9][0-9]'

答案 2 :(得分:-2)

将ISNUMERIC()添加到where子句:

select distinct SUBSTRING(PAPROJNUMBER, 1, 5) AS STUDY_NUMBER
from DBO.PA01201 AS PA01201_1
where PAPROJNUMBER > '0' AND ISNUMERIC(SUBSTRING(PAPROJNUMBER, 1, 5))

或者,您可以放弃>比较:

select distinct SUBSTRING(PAPROJNUMBER, 1, 5) AS STUDY_NUMBER
from DBO.PA01201 AS PA01201_1
where ISNUMERIC(SUBSTRING(PAPROJNUMBER, 1, 5))