declare @t int,@database varchar(100)
set @database='NorthWind.dbo.sysobjects'
exec sp_executesql N'select @t=count(*) from '+@database+' where name=''products''', N'@t int out',@t out
select @t为什么总报错呢?

解决方案 »

  1.   

    declare @t int,@database varchar(100)
    set @database='NorthWind.dbo.sysobjects'
    exec sp_executesql N'select @n=count(*) from '+@database+' where name=''products''', N'@n int output',@n=@t output
    select @t
      

  2.   


    declare @t int,@database nvarchar(100),@sql nvarchar(4000)
    set @database='NorthWind.dbo.sysobjects'
    set @sql=N'select @t=count(*) from '+ @database + ' where name=''products'''
    exec sp_executesql @sql, N'@t int out',@t out
    select @t
      

  3.   


    declare @t int,@database varchar(100)
    set @database='NorthWind.dbo.sysobjects'
    DECLARE @SQL NVARCHAR(4000)
    SET @SQL= N'select @t=count(*) from '+@database+' where name=''products'''
     
    exec sp_executesql @SQL, N'@t int out',@t out
    select @t
      

  4.   

    declare @t int,@database varchar(100),@sql nvarchar(4000)
    set @database='NorthWind.dbo.sysobjects'
    set @sql=N'select @t=count(*) from '+@database+' where name=''products'''
    exec sp_executesql @sql, N'@t int out',@t out
    select @t
      

  5.   

    注意二點:
    1.不能在 exec sp_executesql 後面進行sql字串組合。
    help說明摘要:更複雜的 Unicode 運算式是不允許的 (例如以 + 運算子串連二個字串2.必須是nvarchar
    help說明摘要:包含 Transact-SQL 陳述式或批次的 Unicode 字串
      

  6.   

    exec sp_executesql  组合问题
      

  7.   

    declare @t int
    seclare @database varchar(100)
    set @database='NorthWind.dbo.sysobjects'
    exec sp_executesql N'select @t=count(*) from '+@database+' where name=''products''', N'@t int out',@t output 
    select @t
      

  8.   

    declare @t int
    seclare @database varchar(100)
    set @database='NorthWind.dbo.sysobjects'
    exec sp_executesql N'select @t=count(*) from '+@database+' where name=''products''', N'@t int outout',@t output 
    select @t
      

  9.   


    declare @t int,@database varchar(100),@sql nvarchar(4000)
    set @database='NorthWind.dbo.sysobjects'
    set @sql=N'select @t=count(*) from '+@database+' where name=''products'''
    exec sp_executesql @sql, N'@t int out',@t out
    select @t