SQL Server - 声明变量但仍然说“必须声明标量变量”

时间:2012-12-06 18:56:40

标签: sql-server

我正在尝试在Microsoft SQL Server上运行这组SQL命令,但我收到此错误:

  

Msg 137,Level 15,State 1,Line 1
  必须声明标量变量“@dbstatus”。

我以为我确实声明了变量,所以我不确定为什么它仍然会抛出错误?

DECLARE @dbname nvarchar(100) 
DECLARE @dbstatus varchar(500) 
DECLARE @sqlCommand NVARCHAR(1000) 
create table #temptable (dbname nvarchar(100), status varchar(500))

DECLARE c1 CURSOR READ_ONLY 
FOR 
   SELECT '[' + name + ']'   FROM sys.databases WHERE name = 'EDDS1084543'

OPEN c1  
FETCH NEXT FROM c1 INTO @dbname 

WHILE @@FETCH_STATUS = 0 
BEGIN            
      SET @sqlCommand = 'SET @dbstatus = (SELECT Status FROM ' + @dbname + '.[EDDSDBO].[dtSearchIndex])'   

      EXECUTE sp_executesql @sqlCommand

      INSERT INTO #tempTable(dbname, [status])VALUES (@dbname, @dbstatus)

      FETCH NEXT FROM c1 INTO @dbname   
END   

CLOSE c1 
DEALLOCATE c1 

2 个答案:

答案 0 :(得分:8)

EXEC / sp_executesql为SQL Server创建一个新连接(SPID),这不是您当前的会话,因此无法查看该变量。检查the documentation

基本上,您必须声明要传递给调用的参数,并为其赋值。在这种情况下,两者都必须包括OUTPUT说明符。

  EXECUTE sp_executesql @sqlCommand, '@dbstatus varchar(500) output', @dbstatus output

答案 1 :(得分:3)

问题在于:

  SET @sqlCommand = 'SET @dbstatus = (SELECT Status FROM ' + @dbname + '.[EDDSDBO].[dtSearchIndex])'   
  EXECUTE sp_executesql @sqlCommand

这会导致服务器将@sqlCommand的值作为独立语句执行。在此语句中,@dbstatus尚未声明为变量,因此出现错误。这就是执行的内容:

SET @dbstatus = (SELECT Status FROM [value in @dbname].[EDDSDBO].[dtSearchIndex])

请改为尝试:

WHILE @@FETCH_STATUS = 0 
BEGIN            
      SET @sqlCommand = 'SET @dbstatus = (SELECT Status FROM ' + @dbname + '.[EDDSDBO].[dtSearchIndex])'   
      EXECUTE sp_executesql @sqlCommand, '@dbstatus varchar(500) output', @dbstatus output
      INSERT INTO #tempTable(dbname, [status])VALUES (@dbname, @dbstatus)
      FETCH NEXT FROM c1
      INTO @dbname   
END