求教一句sql查询语句
具体情况是在一张表内有两个字段,假设为 :num1 num2
分别表示开始数字与结束数字,例如有数据为:
1 10
11 20
21 30
31 40
41 50
以上5条数据;
现在我这里给予的查询条件是一个区间,比如是13-35
查询到的数据应该是后面四条,请问,这种情况如何查询比较好?
[解决办法]
- SQL code
--> 测试数据:[tb]IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]GO CREATE TABLE [tb]([num1] INT,[num2] INT)INSERT [tb]SELECT 1,10 UNION ALLSELECT 11,20 UNION ALLSELECT 21,30 UNION ALLSELECT 31,40 UNION ALLSELECT 41,50 UNION ALLSELECT 20,10 --增加一个[num2]>[num1]的--------------开始查询----------------------------13-35--应该是下面三行才合理吧SELECT * FROM [tb] WHERE [num2]>13 AND [num2]>[num1] AND [num1]<35----------------结果----------------------------/* num1 num2----------- -----------11 2021 3031 40(3 行受影响)*/
[解决办法]
- SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([id] int,[value] int)insert [test]select 1,10 union allselect 11,20 union allselect 21,30 union allselect 31,40 union allselect 41,50declare @str varchar(1000)set @str='13-35'select @str=REPLACE(@str,'-',' and ')exec('select * from test where [value] between '+@str+' or id between '+@str)/*id value11 2021 3031 40*/