table1
bh    tableKind
1       10
3        10-----------
字段tableKind用变量表示,如下查询,但是查不到记录,请问大家哪里错了?
declare @a varchar(50)
set @a='tableKind'
select * from table1 where '+@a+'='10'

解决方案 »

  1.   

    declare @a varchar(50)
    set @a='tableKind'
    exec('select * from table1 where '+@a+'='10' ')
      

  2.   

    --这样?
    create table tb(bh int,tableKind int)
    insert into tb select 1,10
    union all select 3,10declare @a varchar(50)
    set @a='tableKind'
    exec('select * from tb where '+@a+'=10')drop table tb
      

  3.   

    --如果是字符型
    create table tb(bh varchar(10),tableKind varchar(10))
    insert into tb select '1','10'
    union all select '3','10'declare @a varchar(50)
    set @a='tableKind'
    exec('select * from tb where '+@a+'=''10''')drop table tb
      

  4.   

    --要用动态SQL
    declare @a varchar(50)
    set @a='tableKind'
    exec('select * from table1 where '+@a+'=''10'' ')
      

  5.   

    请问大家动态sql和直接写的sql有什么区别么?
      

  6.   

    declare @a varchar(50)
    set @a='tableKind'
    exec('select * from tb where '+@a+'=10')