looking for a brokerage account or IRA... click here Add To Favorites
return to index 

t-SQL Cursor

In cases where you have lots of data and partition it across multiple databases, you may need to pull data from table in all of the databases. I cursor is an easy way to do this. If the standard option you want to perform is

SELECT * FROM DB1.dbo.Partition

Then you can use a cursor to to execute that operation across all of the databases.

DECLARE @SQL NVARCHAR(MAX),
    @DatabaseName VARCHAR(100)

DECLARE a CURSOR FOR
    SELECT DatabaseName FROM #DataBase
OPEN a

FETCH NEXT FROM a INTO @DatabaseName 
WHILE (@@FETCH_STATUS<>-1)
BEGIN
    SET @SQL='SELECT * FROM ['+@DatabaseName+'].dbo.Partition'
    EXEC (@SQL)

    FETCH NEXT FROM a INTO @DatabaseName 
END

Additional Interesting Articles

C# MailMessage Example
Block File Leechers Using PHP
Pearson Coefficient
SQL Difference Between IS NULL and =NULL
SQL Check Existence of Table or Temp Table
PHP All Over Again

©2008 AndrewKimball.com