具体情况是在一张表内有两个字段,假设为  :num1   num2
分别表示开始数字与结束数字,例如有数据为:   
1      10
11     20
21     30
31     40
41     50
以上5条数据;现在我这里给予的查询条件是一个区间,比如是13-35
查询到的数据应该是后面四条,请问,这种情况如何查询比较好?
                                             

解决方案 »

  1.   

    --> 测试数据:[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 ALL
    SELECT 11,20 UNION ALL
    SELECT 21,30 UNION ALL
    SELECT 31,40 UNION ALL
    SELECT 41,50 UNION ALL
    SELECT 20,10 --增加一个[num2]>[num1]的
    --------------开始查询--------------------------
    --13-35
    --应该是下面三行才合理吧
    SELECT * FROM [tb] WHERE [num2]>13 AND [num2]>[num1] AND [num1]<35
    ----------------结果----------------------------
    /* 
    num1        num2
    ----------- -----------
    11          20
    21          30
    31          40(3 行受影响)*/
      

  2.   

    因为给的条件是13到35啊。
    NND,看错了,是中间三条才对呵呵
      

  3.   


    --> 测试数据:[test]
    if object_id('[test]') is not null 
    drop table [test]
    create table [test]([id] int,[value] int)
    insert [test]
    select 1,10 union all
    select 11,20 union all
    select 21,30 union all
    select 31,40 union all
    select 41,50
    declare @str varchar(1000)
    set @str='13-35'
    select @str=REPLACE(@str,'-',' and ')
    exec('select * from test where [value] between '+@str)
    /*
    id value
    ----------------
    11 20
    21 30
    */不知道你的结果是怎么出来的
      

  4.   


    --> 测试数据:[test]
    if object_id('[test]') is not null 
    drop table [test]
    create table [test]([id] int,[value] int)
    insert [test]
    select 1,10 union all
    select 11,20 union all
    select 21,30 union all
    select 31,40 union all
    select 41,50
    declare @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 value
    11 20
    21 30
    31 40
    */