循环数据库时游标结果不一致
我有几个名称非常相似的数据库(my-db-1、my-db-2、my-db-3、my-db-4)。我想在每个数据库上执行相同的存储过程。我决定使用游标。但是,我遇到了一些奇怪的问题。首先,这是我通过 SQL Server Management Studio 2008 执行的简单代码。
DECLARE @db_cursor CURSOR
DECLARE @name varchar(255)
DECLARE @Sql nvarchar(4000)
SET @db_cursor = CURSOR FOR
SELECT name FROM sys.databases WHERE name LIKE 'my-db-%'
OPEN @db_cursor
FETCH NEXT FROM @db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Sql = 'Use [' + @name + ']; PRINT DB_NAME();'
exec sp_sqlexec @Sql
FETCH NEXT FROM @db_cursor INTO @name
END
CLOSE @db_cursor
DEALLOCATE @db_cursor
在 2 秒内连续执行多次,我得到奇怪的结果:
Execution1:
my-db-1
my-db-2
my-db-3
my-db-4
Execution2:
my-db-1
my-db-2
Execution3:
my-db-1
my-db-2
my-db-3
my-db-4
Execution4:
my-db-1
看起来完全是随机的。有时我会在 10 次执行后打印所有 4 个数据库。有时,仅执行 2 次后,只会打印 1 个数据库。
此 SQL 正在 Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) 2010 年 4 月 2 日 15:48:46 版权所有 (c) Windows NT 6.1(内部版本 7600:)上的 Microsoft Corporation Developer Edition(64 位)上执行通过 Microsoft SQL Server Management Studio 10.50.1600.1
有人有什么想法吗?
I have several databases named very similar (my-db-1, my-db-2, my-db-3, my-db-4). I want to execute the same stored procedure on each of these databases. I decided to use cursors. However, I am getting some strange issues. First here is my simple code that I am executing through SQL Server Management Studio 2008.
DECLARE @db_cursor CURSOR
DECLARE @name varchar(255)
DECLARE @Sql nvarchar(4000)
SET @db_cursor = CURSOR FOR
SELECT name FROM sys.databases WHERE name LIKE 'my-db-%'
OPEN @db_cursor
FETCH NEXT FROM @db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Sql = 'Use [' + @name + ']; PRINT DB_NAME();'
exec sp_sqlexec @Sql
FETCH NEXT FROM @db_cursor INTO @name
END
CLOSE @db_cursor
DEALLOCATE @db_cursor
Executing this multiple times in a row within 2 seconds, I get strange results:
Execution1:
my-db-1
my-db-2
my-db-3
my-db-4
Execution2:
my-db-1
my-db-2
Execution3:
my-db-1
my-db-2
my-db-3
my-db-4
Execution4:
my-db-1
It seems like its completely random. Sometimes I'll get all 4 databases to print after 10 executions. Sometimes after just 2 executions only 1 database will get printed.
This SQL is executing on Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: ) through Microsoft SQL Server Management Studio 10.50.1600.1
Does anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试将光标声明为
FAST_FORWARD
。默认是可更新游标,这些所需的更新锁可能与访问 sys.databases 的另一个进程冲突。
参考:声明光标
Try declaring your cursor as
FAST_FORWARD
.The default is an updateable cursor and these required update locks probably conflict with another process accessing
sys.databases
Ref.: DECLARE CURSOR