从char列中选择正数

时间:2015-06-03 21:46:44

标签: sql-server

我有一个char列的表格,希望从中获得正数。

DECLARE @TABELA TABLE (ID VARCHAR(20))
INSERT INTO @TABELA VALUES ('-12'),('10'),('25'),('12A')

我尝试了最明显的查询:

select * from @TABELA where ID > 0 and ISNUMERIC(ID) = 1

select *
from (select * from @TABELA where ISNUMERIC(ID) = 1) A
where ID  > 0

;WITH A AS (select * from @TABELA where ISNUMERIC(ID) = 1)
select * from A where ID  > 0

但他们没有工作并返回错误:

  

将varchar值'12A'转换为数据类型时转换失败   INT

以下一个有效,但我担心无法保证它在任何情况下都有效,因为我无法保证评估where子句的顺序:

select * from @TABELA where ISNUMERIC(ID) = 1 and ID  > 0

我认为另一种选择非常难看:

select *
from (
    select case when ISNUMERIC(ID) = 1 then 
            case when ID > 0 
                then ID 
            end
        end ID
    from @TABELA 
) A
where ID is not null

有没有办法在一个查询中获得正数?

3 个答案:

答案 0 :(得分:2)

试试这个:

select * from table
where id not like '%[^0-9]%' and id not like '%-%'

小提琴http://sqlfiddle.com/#!3/c769c/2

答案 1 :(得分:0)

您可以编写一个这样的简单查询来仅检索正ID并忽略非数字:

SELECT * FROM @TABELA
WHERE ISNUMERIC(ID) = 1 AND CAST(ID as int) >= 0

答案 2 :(得分:0)

由于@John建议try_cast,我意识到我可以使用CROSS APPLY为所有版本的SQL SERVER执行此操作:

select ID_NUM 
from @TABELA
cross apply (select case when ISNUMERIC(ID) = 1 then ID else NULL end) B(ID_NUM)
where ID_NUM > 0

或者像他之后建议的那样:

select *
from @TABELA
where cast(case when isnumeric(id) = 1 then id end as int) >= 10