E N D
Cursors in SQL Understanding Cursors, Types, Syntax & Usage
Introduction to Cursors • A cursor is a database object used to retrieve data row by row. • Unlike a SELECT statement, which retrieves all rows at once, a cursor processes rows individually. • Cursors are commonly used when operations need to be performed on each row separately.
Types of Cursors 1. Implicit Cursor: Automatically created by SQLwhen DML statements are executed. 2. Explicit Cursor: Defined by the user for complex row-wise operations. 3. Static Cursor: Works with a snapshot of data. 4. Dynamic Cursor: Reflects real-time changes in thedatabase. 5. Forward-Only Cursor: Can only move forward throughrecords. 6.Scrollable Cursor: Can move both forward andbackward.
How Cursors Work • 1. Declare the cursor. • 2. Open the cursor. • 3. Fetch rows one by one. • 4. Process each row. • 5. Close the cursor. • 6. Deallocate the cursor.
Step 1: Declare a Cursor Define the cursor and specify the SQL query that retrieves the data. sql DECLARE my_cursor CURSOR FOR SELECT column1, column2 FROM my_table; Step 2: Open the Cursor Execute the SQL query and make the result set available. sql OPEN my_cursor; Step 3: Fetch Rows Retrieve data from the cursor one row at a time using FETCH. sql FETCH NEXT FROM my_cursor INTO @var1, @var2;
Step 3: Fetch Rows Retrieve data from the cursor one row at a time using FETCH. sql FETCH NEXT FROM my_cursor INTO @var1, @var2; Step 4: Process the Data You can use a WHILE loop to process each row. sql WHILE @@FETCH_STATUS = 0 BEGIN -- Process data here (e.g., print, insert into another table) FETCH NEXT FROM my_cursor INTO @var1, @var2; END; Step 5: Close and Deallocate the Cursor • CLOSE releases the current result set. • DEALLOCATE removes the cursor definition. sql CLOSE my_cursor; DEALLOCATE my_cursor;
Advantages & Disadvantages Advantages: • Allows row-by-row processing. • Useful for handling complex business logic. Disadvantages: • Slower than set-based operations. • Consumes more memory and processing power.