Question : In an SQL Server Stored Procedure, how do I declare a cursor using a Where clause passed in as a parameter?

Using SQL Server 2005 Express, I would like to create a Stored Procedure that creates a cursor based on a SELECT statement that uses a WHERE clause passed in to the SP as a parameter.
The SP would then do further UPDATE commands using the content of the cursor.

I have previously been able to do separate tasks, ie
1) Have an SP execute an SQL statement using a passed-in WHERE clause
    SET @strSQLCommand = 'DELETE FROM TBL_TempBarcodeData WHERE ' + @paramWhereClause
    EXEC (@strSQLCommand)

and
2) Create a cursor to work with inside an SP
       DECLARE myCursor CURSOR FOR
       SELECT        Tran_MasterUniqID, Tran_ThisPaid, Tran_ThisDiscnt, Tran_NewFlagComplete
       FROM       TBL_WORK_TranAllocs
       WHERE      Tran_AddrKind = @paramAddrKind AND TBL_WORK_TranAllocs.Tran_AddrCode =  @paramAddrCode AND (TBL_WORK_TranAllocs.Tran_ThisPaid<>0 OR TBL_WORK_TranAllocs.Tran_ThisDiscnt<>0)

(These two examples are unrelated of course, and are just to demonstrate what I have been able to get working inside SPs in the past.)

This time I would like to combine both these types of actions, ie create a cursor using a SELECT statement with a passed-in WHERE clause. My own attempts have failed thus far.

Can anyone show me the SQL syntax that would achieve this inside an SP?

Many thanks,

Answer : In an SQL Server Stored Procedure, how do I declare a cursor using a Where clause passed in as a parameter?

Colin,

As long as your app is the only one passing the WHERE clause, then you are probably reasonably safe.  The issue is not your code, though.  SQL Injections are normally not the sort of thing the developer builds into his app but, rather, the sort of thing that some malicious soul who stumbles upon your database does out of pure meanness.

Perhaps, instead of passing the WHERE clause, you might want to consider passing the various parameters that were selected for the report.  You could pass NULL values for unselected parameters, if need be.  Then, within the SP, execute your updates based upon the parameters instead of upon the "Magic Where Clause".  By using the parameters, you can preclude the injection attack (mostly because it would cause an invalid SQL Statement instead of just executing.)

All I am pointing out is that the technique you are using (or trying to use) is inherently unsafe and should never be a part of a production database application.  It violates the rules of all known "Best Practices".

Random Solutions  
 
programming4us programming4us