当我运行以下SIMPLE代码时,我收到以下错误:"必须声明表变量" @ tableName"。"
我不确定原因:我在WHILE语句中尝试DECLAREing变量,但我仍然得到同样的愚蠢错误。 我需要做的就是查询我的数据库(myDB)中的所有表并输出它。
DECLARE @tableName VARCHAR(80)
DECLARE TableName_Cursor CURSOR FAST_FORWARD FOR
SELECT TABLE_NAME FROM myDB.INFORMATION_SCHEMA.Tables
OPEN TableName_Cursor
FETCH NEXT FROM TableName_Cursor INTO @tableName
WHILE @@FETCH_STATUS =0
BEGIN
--DECLARE @tableName VARCHAR(80)
--USE myDB
SELECT * FROM @tableName
FETCH NEXT FROM TableName_Cursor INTO @tableName
END
CLOSE TableName_Cursor
DEALLOCATE TableName_Cursor
非常感谢你的帮助!
答案 0 :(得分:3)
与variable
范围无关
您需要Dynamic SQL
才能执行此操作
Declare @sql varchar(8000)= ''
WHILE @@FETCH_STATUS =0
BEGIN
Set @sql = ''
Set @sql = 'SELECT * FROM ' +QUOTENAME(@tableName)
EXEC(@sql)
FETCH NEXT FROM TableName_Cursor INTO @tableName
END