我的库表为
id   name  createdate
1    aaa    2006-10-30
2    bbb    2006-10-31
3    ccc    2006-11-1我有一个参数 @Id 如果@id=''的时候则查询结果为所有数据按逆序排列
如果参数 @id='2' 则 只找到id='2'的这条记录select * from table where id=@id and XXXXXX(这里不会写了) order by createdate desc

解决方案 »

  1.   

    select * from table where case when @id='' then 1=1 else id =@id end order by createdate desc
      

  2.   


    declare @t table(id varchar(5),   name varchar(5),  createdate datetime)
    insert into @t select
    '1',    'aaa',    '2006-10-30'
    union all select
    '2',    'bbb',    '2006-10-31'
    union all select
    '3',    'ccc',    '2006-11-1'
    declare @id int
    set @id=''
    select * from @t where id=@id or @id='' order by id desc
    (所影响的行数为 3 行)id    name  createdate                                             
    ----- ----- ------------------------------------------------------ 
    3     ccc   2006-11-01 00:00:00.000
    2     bbb   2006-10-31 00:00:00.000
    1     aaa   2006-10-30 00:00:00.000(所影响的行数为 3 行)
      

  3.   

    louifox(兰陵笑笑生) 的方法有效 多谢 马上给分 xiaoku(野蛮人(^v^))您的方法我测试在.net的查询分析器里面没法使用 因为会报错 为申明变量@id