16

这可能很简单,但我不是 SQL 专家,所以我迷路了。我了解 sql 获取您的查询并按特定顺序执行它,我相信这就是为什么此查询不起作用的原因:

select * from purchaseorders
where IsNumeric(purchase_order_number) = 1
and cast(purchase_order_number as int) >= 7

大多数 purchar_order_number 字段是数字的,但我们最近引入了字母数字字段。我试图获取的数据是查看“7”是否大于最高数字 purchase_order_number。

Numeric() 函数可以很好地过滤掉字母数字字段,但是进行后续的强制转换比较会引发此错误:

Conversion failed when converting the nvarchar value '124-4356AB' to data type int.

我不是在问错误是什么意思,这很明显。我在问是否有一种方法可以在单个查询中完成我想要的,最好是在 where 子句中,因为 ORM 约束。

4

3 回答 3

31

这对你有用吗?

select * from purchaseorders
where (case when IsNumeric(purchase_order_number) = 1
       then cast(purchase_order_number as int)
       else 0 end) >= 7
于 2012-11-16T16:45:58.797 回答
1

您可以使用子选择进行选择

select * from (
select * from purchaseorders
where IsNumeric(purchase_order_number) = 1) as correct_orders
where cast(purchase_order_number as int) >= 7
于 2012-11-16T16:30:05.783 回答
1

尝试这个:

select * from purchaseorders
where try_cast(purchase_order_number as int) >= 7
于 2017-02-15T16:26:34.887 回答