Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何通过游标在多个表上执行逻辑?(表名位于光标中)_Sql_Sql Server_Sql Server 2008_Cursor - Fatal编程技术网

Sql 如何通过游标在多个表上执行逻辑?(表名位于光标中)

Sql 如何通过游标在多个表上执行逻辑?(表名位于光标中),sql,sql-server,sql-server-2008,cursor,Sql,Sql Server,Sql Server 2008,Cursor,我觉得这是一项非常基本的数据库工作,但我不适合。我试图从系统表中获取所有墓碑表的列表,并将结果存储在游标中。然后,我尝试对这些表中的每一个执行一些逻辑,但我在执行时遇到了困难 任何帮助都将不胜感激 以下是我得到的错误: 必须声明表变量“@tablename” 代码如下: declare tombstonetables cursor for (select name from sys.objects where name like'%tombstone%' and type = 'U'--fo

我觉得这是一项非常基本的数据库工作,但我不适合。我试图从系统表中获取所有墓碑表的列表,并将结果存储在游标中。然后,我尝试对这些表中的每一个执行一些逻辑,但我在执行时遇到了困难

任何帮助都将不胜感激

以下是我得到的错误: 必须声明表变量“@tablename”

代码如下:

declare tombstonetables cursor for 
(select name from sys.objects
where 
name like'%tombstone%'
and type = 'U'--for user_table
)

Print 'Begin purging tombstone tables'

declare @tablename varchar(250)
open tombstonetables

fetch next from tombstonetables into @tablename

WHILE @@FETCH_STATUS = 0
begin
select * from @tablename--real logic goes here later

fetch next from tombstonetables into @tablename

end
close tombstonetables

deallocate tombstonetables

看起来你需要使用

这里是一个简单的漫游参考

您可能需要利用

下面是一个将动态SQL与您的示例一起使用的简单示例

DECLARE @DynamicSQL nvarchar(100)

WHILE @@FETCH_STATUS = 0
begin
SET @DynamicSQL = 'select * from ' + @tablename --real logic goes here later
EXEC @DynamicSQL
fetch next from tombstonetables into @tablename

end

看起来你需要使用

这里是一个简单的漫游参考

您可能需要利用

下面是一个将动态SQL与您的示例一起使用的简单示例

DECLARE @DynamicSQL nvarchar(100)

WHILE @@FETCH_STATUS = 0
begin
SET @DynamicSQL = 'select * from ' + @tablename --real logic goes here later
EXEC @DynamicSQL
fetch next from tombstonetables into @tablename

end

如果我的某些语言语法不正确,我很抱歉。如果我的某些语言语法不正确,我很抱歉。+1:为了澄清操作,将变量名用作表名的唯一方法是使用动态sql。+1:为了澄清操作,将变量名用作表名的唯一方法是使用动态sql。