IF  exists(N'select '+@id+' from '+@tableName+' where '+@id+'='+cast(@Col_Id as nvarchar(20)))这么写为什么不对呢?

解决方案 »

  1.   

    当字段或者表名是变量时,需要使用动态SQL
      

  2.   

    这两个@id、@Col_Id是什么意思 
      

  3.   

    @Col_Id 是传进来的int型的值,假设是100if(@Col_Type=1)
    BEGIN
    set @tablename='table1'
    set @id='id'
    end
    else
    BEGIN
    set @tablename='table2'
    set @id='f_id'
    end根据传进来的类型,查询不同的表关键是下边这句一直写不出来,谢谢IF  exists(N'select '+@id+' from '+@tableName+' where '+@id+'='+cast(@Col_Id as nvarchar(20)))
    BEGIN
    执行插入语句
    END
      

  4.   

    declare @sql varchar(8000)
    set @sql=N'if exists(select '+@id+' from '+@tableName+' where '+@id+'='+cast(@Col_Id as nvarchar(20))+')
             begin
             end '
    exec(@sql)
      

  5.   

    没别的办法,不支持传递变量作为表名或字段名去直接查询
    select * from @table,这样是错的,所以只能全部放在动态语句中
      

  6.   

    print 出来你括号内的内容