CLOSE

CLOSE in SQL is a command used in the context of cursors. It effectively terminates a cursor that has been opened and populated with a fetch statement, thereby ceasing any further operations within that cursor. The associated resources are freed up, but the cursor is still available for re-open.

Example

DECLARE
emp_cursor CURSOR FOR
SELECT * FROM employees;
BEGIN
OPEN emp_cursor;
CLOSE emp_cursor;
END;

Output

This script won’t generate a visible output, because the cursors don’t produce visible outputs in Oracle database.

Explanation

In the Example, a cursor emp_cursor is declared, which fetches all records from the employees table. The OPEN statement opens the cursor, making it ready to fetch the data. The CLOSE statement, which is the focus of this example, is used to close the cursor emp_cursor after the usage. Since a closed cursor cannot be referenced, the CLOSE statement is essential to free up the memory in the database environment.

Example

DECLARE @sales CURSOR;
SET @sales = CURSOR FOR
SELECT * FROM Sales
OPEN @sales
--perform operations
CLOSE @sales

Output

Command(s) completed successfully.

Explanation

In the above SQL Server code snippet, a cursor named @sales is being declared and set to select all records from the Sales table. The OPEN statement initiates the cursor, and after executing required operations, the CLOSE statement is used. This closes the cursor and releases the current result set. However, it does not deallocate resources. A cursor must be closed before it can be reopened. The output shows that the commands have been carried out successfully.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.