有一个语句我不想用字符串转换的形式写,那样太烦了,我想直接在sql里面写,但是不知道怎么实现,下面是我用字符串转换的形式写出来的一个语句
declare @whe nvarchar(1000)
set @whe=''
if type=1
set @whe=' where aa=1'
if type=2
set @whe=' where aa=2'
declare @sqlstr nvarchar(1000)
set @sqlstr = 'select * from a '+@whe
exec(@sqlstr)如果不用字符串转换的形式请问怎么写上面的语句呢
declare @whe nvarchar(1000)
set @whe=''
if type=1
set @whe=' where aa=1'
if type=2
set @whe=' where aa=2'
//下面我就是直接想用查询语句写出来,请大哥大姐们帮帮忙!
select * from a + @whe

解决方案 »

  1.   

    declare @sqlstr nvarchar(1000) 
    set @sqlstr = 'select * from a where aa='+ltrim(type) 
    exec(@sqlstr)
      

  2.   

    select * from a where aa =cast(type as char)
      

  3.   

    全不用字符串可以这样,select * from a where aa=@type --@type作为变量传入
      

  4.   

    没有一个是对的,没懂我的意思,1楼给我的结果还是一个字符串形式的查询语句,2楼跟3楼的意思都一样,你们有没有试过查询语句+字符串能正常查询吗,直接就报错了!
    select * from a + @whe 这句话前面是sql查询语句,@whe这句话我不知道怎么样转换成查询语句啊,我只知道1楼的做法,就是把整个语句都转换为字符串执行,但那样太烦了啊!
      

  5.   

    create table A(nameA varchar(3),name2 varchar(4),type int)
    insert A select 'a','aa',1 union all
    select 'b','bb',2  union all
    select 'b','dd',2  union all
            select 'c','cc',3select * from A where name2=(case when type=2 then 'bb' when type=1 then 'aa' end )drop table AnameA  name2   type
    a aa 1
    b bb 2
      

  6.   

    declare @type int
    select @type=type
    select * from a where aa=@type
      

  7.   

    select * from A where name2=
    (case when type=2 then 'bb' when type=1 then 'aa' end )
      

  8.   


    select * from a 
    where ((aa=1 and type=1) or (aa=2 and type=2) or (aa=3 and type=3))把1,2,3换成你相应的参数或者值
      

  9.   

    declare @aa int
    set @aa=3
    select * from a where 字段名=@aa