Skip to main content

Posts

Showing posts from December, 2007

Avoid Cursor In row by row processessing

Cursors exist because there are situations that row-by-row processing is inevitable. However as they are resource intensive, developers always try to refine their codes and bypass cursors using T-SQL tricks. Not all scenarios are capable for this replacement, but I have seen many of them! One of the common usages of cursors is inside triggers for processing the Deleted and Inserted tables. At the time of writing this article, SQL Server does not support any mechanism to fire a trigger for each row separately when a DML statement affects more than one row. As an example, an Insert command is inserting 5 records (from a query) into a table. Your trigger needs to retrieve each PK value from Inserted table and send it to a particular Stored Procedure for some processes. Iterating through a cursor made of PKs might seem the first option. However in this case we can use the power of variables that live within a query, then Dynamic T-SQL Execution finalizes the trick! Let's create neces...