Professional Documents
Culture Documents
Author:
https://www.mssqltips.com/sqlservertip/1599/sql-server-cursor-example/
Problem
In my T-SQL code I always use set based operations. I have been told these types
of operations are what SQL Server is designed to process and it should be quicker
than serial processing. I know cursors exist but I am not sure how to use them.
Can you provide some cursor examples? Can you give any guidance on when to use
cursors? I assume Microsoft created them for a reason so they must have a place
where they can be used in an efficient manner.
Solution
In some circles cursors are never used, in others they are a last resort and in
other groups they are used regularly. In each of these camps they have different
reasons for their stand on cursor usage. Regardless of your stand on cursors they
probably have a place in particular circumstances and not in others. So it boils
down to your understanding of the coding technique then your understanding of the
problem at hand to make a decision on whether or not cursor based processing is
appropriate or not. To get started let's do the following:
--BEGIN
SET @path = 'C:\Backup\'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
CLOSE db_cursor
DEALLOCATE db_cursor
--END