http://expert.csdn.net/Expert/topic/2364/2364046.xml?temp=.829693
[交流]动态SQL语句

解决方案 »

  1.   

    exec('select' + @ifwj + '=count(*) from' + @bblb + 'where xmjlb=' + @xmjlb + 'and xmmc=' + @xmmc + 'and year(a.insert_time)=' + @nd + ' and month(a.insert_time)=' + @yf)
      

  2.   

    select @ifwj=count(*) from @bblb where xmjlb=@xmjlb and xmmc=@xmmc and year(a.insert_time)=@nd and month(a.insert_time)=@yf  --出现错误
       --->
    declare @str nvarchar(4000)
    set @str = 'select @ifwj=count(*) from '+@bblb +'
    where xmjlb='+cast(@xmjlb as varchar(10))+' and xmmc='+cast(@xmmc as varchar(10))
     +'and year(a.insert_time)='
    +cast(@nd as char(4))+' and month(a.insert_time)='+ cast(@yf as char(2))
    exec sp_executesql @str,N'@ifwj int output',@ifwj output
      

  3.   

    alter proc sp_jclc @xmjlb int,@xmmc int,@bblb nvarchar(50),@nd int,@yf int,@mod int,@reid int OUTPUT
    AS
     begin
      set nocount on
      set @reid=0
      declare @ifwj int
      set @ifwj=-1
      
      select @ifwj=是否完结 from 公文 where 流程步ID=@mod and 项目经理部=@xmjlb and 建设项目名称=@xmmc and 报表年=@nd and 报表月=@yf and 类别=1 and 报表类型=@bblb
      if(@ifwj<>-1)  
        begin
         if(@ifwj=0)
            set @reid=1
            return
         if(@ifwj=1)
            set @reid=2
            return
        end
       declare @a nvarchar(4000)
       set @a='select @ifwj=count(*) from '+@bblb+' where xmjlb='+cast(@xmjlb as varchar(10))+' and xmmc='+cast(@xmmc as varchar(10))+' and year(a.insert_time)='+cast(@nd as varchar(10))+' and month(a.insert_time)='+cast(@yf as varchar(10))
       exec sp_executesql @a,N'@ifwj int output',@ifwj output
       if(@ifwj=0)
        begin
         set @reid=3
         return
        end
    end
      

  4.   

    使用动态SQL语句!
    exec('select' + @ifwj + '=count(*) from' + @bblb + 'where xmjlb=' + @xmjlb + 'and xmmc=' + @xmmc + 'and year(a.insert_time)=' + @nd + ' and month(a.insert_time)=' + @yf)
      

  5.   

    --变量不能直接用于from语句,需要改为:alter proc sp_jclc @xmjlb int,@xmmc int,@bblb nvarchar(50),@nd int,@yf int,@mod int,@reid int OUTPUT
    AS
     begin
      set nocount on
      set @reid=0
      declare @ifwj int
      set @ifwj=-1
      
      select @ifwj=是否完结 from 公文 where 流程步ID=@mod and 项目经理部=@xmjlb and 建设项目名称=@xmmc and 报表年=@nd and 报表月=@yf and 类别=1 and 报表类型=@bblb
      if(@ifwj<>-1)  
        begin
         if(@ifwj=0)
            set @reid=1
            return
         if(@ifwj=1)
            set @reid=2
            return
        end
       declare @a nvarchar(4000)
       set @a='select @ifwj=count(*) from '+@bblb+' where xmjlb='+cast(@xmjlb as varchar(10))+' and xmmc='+cast(@xmmc as varchar(10))+' and year(a.insert_time)='+cast(@nd as varchar(10))+' and month(a.insert_time)='+cast(@yf as varchar(10))
       exec sp_executesql @a,N'@ifwj int output',@ifwj output
       if(@ifwj=0)
        begin
         set @reid=3
         return
        end
    end