Dinamic SQL & Cursor
Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET or any other programming language. But how do you do this from within a SQL Server stored procedure?
Dinamic SQL Dynamic SQL is a term used to mean SQL code that is generated programatically (in part or fully) by your program before it is executed. As a result it is a very flexable and powerful tool. You can use dynamic SQL to accomplish tasks such as adding where clauses to a search based on what fields are filled out on a form or to create tables with varying names.
How To Run Dinamic SQL SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql
Parameters - EXEC – SP_EXECUTESQL varchar(75) = 'London' SELECT * FROM customers WHERE City varchar(1000) varchar(75) varchar(75) = 'CustomerID, ContactName, City' = '''London''' = 'SELECT ' + ' FROM customers WHERE City = ' EXEC nvarchar(1000) varchar(75) varchar(75) = 'CustomerID, ContactName, City' = 'London' = 'SELECT ' + ' FROM customers WHERE City EXECUTE
Dinamic SQL in a Stored Procedure Create Procedure VarChar(100) AS SELECT * Create Procedure VarChar(100) AS VarChar(1000) = 'SELECT * FROM ' EXEC Create Procedure VarChar(100) AS VarChar(1000) = 'SELECT * FROM ' EXEC
SP_EXECUTESQL The system stored procedure sp_executesql behaves very similar to the EXECUTE command, however, it offers two advantages: 1.Parameters can stay in their native data type - with EXECUTE you will have to pass a string; therefore, everything needs to be converted to string data types with EXEC. 2.Query optimizer is more likely to re-use the existing execution plans if you have to run the same query with different parameters. The reason for this is that the text of the query does not change with sp_executesql - with EXEC you pass a different string each time.
SP_EXECUTESQL sp_executesql itionList], The parameters are specified with a name and type. We can specify the parameters for both input and output.
Dinamic SQL Samples (1) CREATE PROCEDURE GENERAL_SELECT varchar(75)) AS BEGIN NVARCHAR(200) = 'SELECT ' + ' FROM ‘ EXECUTE END
Dinamic SQL Samples (2) CREATE PROCEDURE usp_GetNumberOfRecord INT OUTPUT ) AS BEGIN NVARCHAR(2000) NVARCHAR(4000) NVARCHAR(500) = INT OUTPUT' = = COUNT(*)+1 FROM ' @TotalRowsReturned OUTPUT END
Dinamic SQL Samples (3) INT = ‘Customers' EXECUTE = OUTPUT as NextRow
Cursor Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. There are times when you want to loop through a series of rows a perform processing for each row. The should only be used when you truly need to access one row at a time. The only reason for that is to call a stored procedure on each row For example, you can use cursor to include a list of all user databases and make multiple operations against each database by passing each database name as a variable.
Cursor Life Cycle A cursor life cycle can be described as follows: 1.Cursor is declared using the DECLARE CURSOR statement. This statement creates a cursor within SQL Server memory 2.Cursor is activated using OPEN CURSOR statement. At this point you can populate the cursor with a record set. 3.Data is retrieved from the cursor using the FETCH keyword. 4.A WHILE loop is executed within the cursor to perform some operation with the rows in the cursor with the condition that the FETCH command is successful. 5.Cursor is deactivated using CLOSE CURSOR statement. At this point you can't populate the cursor with additional rows. Nor can you work w ith rows within the cursor. However, you can re-open the cursor with OPEN CURSOR statement and perform additional work with the cursor. 6.The cursor is destroyed using DEALLOCATE CURSOR statement. Once the cursor is de-allocated it cannot be reopened.
Cursor Syntax DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR FOR select_statement [FOR {READ ONLY | UPDATE [OF column_name [,...n]]}] OPEN { { [GLOBAL] cursor_name } | cursor_variable_name} FETCH [[ NEXT | PRIOR | FIRST | LAST | ABSOLUTE {n | RELATIVE {n ] FROM ] { { [GLOBAL] cursor_name } ] CLOSE { {[GLOBAL] cursor_name } | cursor_variable_name } DEALLOCATE { { [GLOBAL] cursor_ name }
Cursor Samples nvarchar(40) int CURSOR = CURSOR FOR SELECT ProductName FROM Products FETCH NEXT WHILE = 0 BEGIN PRINT 'Product #' + AS char(3)) SET FETCH NEXT END
Cursor Functions CURSOR_STATUS
valueMeaning 0Successful fetch of a row within a cursor Fetch has failed. This could mean that the cursor has reached the beginning (or end) of the record set. This could also mean that we attempted retrieving a record that does not exist. For instance, if you attempt to grab 51st record within a cursor that has 50 records fetch status will be The fetched row is missing. This means the record you're trying to FETCH has been deleted or its key has been updated since you have opened the cursor. The most commonly used cursor function is This function determines whether FETCH keyword has successfully retrieved a row from the current cursor. can take one of the three values:
Example VARCHAR(85) DECLARE employee_cursor CURSOR FOR SELECT TOP 5 FirstName + ' ' + LastName + ' ' + Title FROM Employees OPEN employee_cursor FETCH NEXT FROM employee_cursor WHILE = 0 BEGIN FETCH NEXT FROM employee_cursor SELECT AS fetch_status END CLOSE employee_cursor DEALLOCATE employee_cursor
function returns the number of rows in the cursor which was opened last on the current connection. This means that if you have 3 cursors open will return the number of rows in the 3rd cursor. can take the following values: valueMeaning -m Cursor is being populated asynchronously. "M" is the value of records in the record set. The cursor is DYNAMIC; that means, it reflects the changes to the data within the cursor. Therefore the number of rows can change due to addition or deletion of rows in the underlying tables. DYNAMIC cursors always return -1 as value of 0 This can mean one of the following: Cursor has not been opened Cursor has no rows Cursor has been closed N Number of rows in the cursor record set. N is reported after the cursor has been fully populated
Example VARCHAR(20) DECLARE MY_CURSOR CURSOR FOR SELECT TOP 3 LASTNAME, FIRSTNAME FROM EMPLOYEES SELECT 'cursor has ' + AS VARCHAR) + ' rows' OPEN MY_CURSOR FETCH NEXT FROM SELECT 'cursor has ' + AS VARCHAR) + ' rows' WHILE = 0 BEGIN FETCH NEXT FROM END CLOSE MY_CURSOR SELECT 'cursor has ' + AS VARCHAR) + ' rows' DEALLOCATE MY_CURSOR
CURSOR_STATUS The CURSOR_STATUS function can be used effectively within a stored procedure that calls another stored procedure. Which returns an output parameter of CURSOR data type. This function can be used with local or global cursors and determines whether or not the stored procedure has returned a cursor with a result set. CURSOR_STATUS( 'local' or 'global', cursor name) CURSOR_STATUS ('variable', cursor variable name)
The values returned by CURSOR_STATUS function CURSOR_ STATUS value Meaning for variableMeaning for cursor name 1 Cursor is open and has at least 1 row DYNAMIC cursors return 1 even if they contain no rows Cursor is open and has at least 1 row DYNAMIC cursors return 1 even if they contain no rows 0Cursor is open but has no rowsCursor has no rows The cursor is closed -2 Cursor wasn't returned by the called procedure OR the cursor was deallocated prior to being assigned to this variable The value of 2 is never returned by CURSOR_STATUS if you refer to cursor name -3 Cursor variable with the specified name does not exist OR the variable exists, but it hasn't been assigned to a cursor returned from the called procedure Cursor with the specified name does not exist
CURSOR_STATUS Example (1) CREATE PROCEDURE CURSOR VARYING OUTPUT) AS BEGIN SET NOCOUNT ON = CURSOR STATIC FOR SELECT LastName, FirstName FROM Employees WHERE LastName END
CURSOR_STATUS Example (2) CREATE PROCEDURE VARCHAR(50) AS SET NOCOUNT ON VARCHAR(20) CURSOR EXECUTE RETURN_EMPLOYEE_NAMES OUTPUT IF = 0 BEGIN PRINT 'no records found' RETURN END ELSE BEGIN FETCH NEXT INTO WHILE = 0 FETCH NEXT INTO END END
CURSOR_STATUS Example (3) EXECUTE call_the_other_procedure 'king'
Daftar Pustaka mic-sql-commands-in-sql-server/ sor_Functions