Inconsistent cursor results when looping over databases
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 开发者_JAVA百科
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?
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
精彩评论