Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

SQL Server Cursor Example

$
0
0
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 included them in SQL Server 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: Look at an example cursor Break down the components of the cursor Provide additional cursor examples Analyze the pros and cons of cursor usage How to Create a SQL Server Cursor Creating a SQL Server cursor is a consistent process, so once you learn the
steps you are easily able to duplicate them with various sets of logic to loop
through data. Let's walk through the steps: First, you declare your variables that you need in the logic. Second you declare cursor with a specific name that you will use
throughout the logic. This is immediately followed by opening the cursor. Third, you fetch a record from cursor to begin the data processing. Fourth, is the data process that is unique to each set of logic.
This could be inserting, updating, deleting, etc. for each row of data that
was fetched. This is the most important set of logic during this process
that is performed on each row. Fifth, you fetch the next record from cursor as you did in step 3 and
then step 4 is repeated again by processing the selected data. Sixth, once all of the data has been processed, then you close cursor. As a final and important step, you need to deallocate the cursor to
release all of the internal resources SQL Server is holding. From here, check out the examples below to get started on knowing when to use
SQL Server cursors and how to do so. Example SQL Server Cursor Here is an example cursor from tip Simple script to backup all SQL Server
databases where backups are issued in a serial manner: DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
SET @path = 'C:\Backup\'
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')
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
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor SQL Server Cursor Components

Based on the example above, cursors include these components:

DECLARE statements - Declare variables used in the code block SET\SELECT statements - Initialize the variables to a specific value DECLARE CURSOR statement - Populate the cursor with values that will be
evaluated NOTE - There are an equal number of variables in the DECLARE CURSOR FOR statement as there are in the SELECT statement. This could
be 1 or many variables and associated columns. OPEN statement - Open the cursor to begin data processing FETCH NEXT statements - Assign the specific values from the cursor to the
variables NOTE - This logic is used for the initial population before the WHILE
statement and then again during each loop in the process as a portion of
the WHILE statement WHILE statement - Condition to begin and continue data processing BEGIN...END statement - Start and end of the code block NOTE - Based on the data processing multiple BEGIN...END statements
can be used Data processing - In this example, this logic is to backup a database to
a specific path and file name, but this could be just about any DML or administrative
logic CLOSE statement - Releases the current data and associated locks, but permits
the cursor to be re-opened DEALLOCATE statement - Destroys the cursor Additional SQL Server Cursor Examples In the example above backups are issued via a cursor, check out these other tips
that leverage cursor-based logic: Managing SQL Server Database
Fragmentation SQL Server script to rebuild
all indexes for all tables and all databases SQL Server Index Analysis Script
for All Indexes on All Tables Standardize your SQL Server
data with this text lookup and replace function Automating Transaction Log Backups
for All SQL Server Databases Searching and finding a string
value in all columns in a SQL Server table Scripting SQL Server Database
Objects Using DMO (Distributed Management Objects) Script to create commands to
disable, enable, drop and recreate Foreign Key constraints in SQL Server Capacity Planning for SQL Server
2000 Database Storage Automate Restoration of Log
Shipping Databases for Failover in SQL Server 2000

Viewing all articles
Browse latest Browse all 3160

Trending Articles