2

我创建了一个表格,其中包含一个名为“Notes”的 nvarchar 字段,人们可以输入他们想要的任何内容(数字或文本)来帮助他们进行搜索。

例如

Table "Customer"
ID  Name  Notes
1   AAA   1234
2   BBB   1235
3   CCC   1236
4   DDD   ABCD

根据这些数据,我只想在 1200 到 1300 之间为 Notes 编写 sql 查询,但它不允许我这样做,因为该字段还包含文本值。

我试过这个

SELECT * 
FROM Customer
WHERE ISNUMERIC(Notes) = 1 AND Notes > 1200 AND Notes < 1300

错误:将 nvarchar 值转换为 int 时转换失败

然后我尝试了这个,我认为这会起作用,但出现了同样的错误

SELECT *
FROM
 (SELECT *
  FROM Customers
  WHERE ISNUMERIC(Notes) = 1 
 ) A
WHERE A.Notes > 1200 AND A.Notes < 1300

有人可以帮忙吗?非常感谢

4

1 回答 1

1

Try this:

SELECT * 
FROM Customer
WHERE (case when ISNUMERIC(Notes) = 1 then cast(Notes as float) end) > 1200 AND
      (case when ISNUMERIC(Notes) = 1 then cast(Notes as float) end) < 1300

This works because the case guarantees the order of evaluation in this case. You could also write this with a subquery:

select *
from (select c.*,
             (case when ISNUMERIC(Notes) = 1 then cast(Notes as float) end) as NotesNum
      from Customer c
     ) c
where NotesNum > 1200 and NotesNum < 1300;

Alternatively, this might come close to what you want:

SELECT * 
FROM Customer
WHERE ISNUMERIC(Notes) = 1 AND
      Notes > '1200' AND Notes < '1300' and len(notes) = 4 and notes not like '%.%'
于 2014-01-28T01:57:29.093 回答