Solved

Updating a Stored Procedure that is using a CURSOR

Posted on 2016-09-29
2
51 Views
Last Modified: 2016-09-29
I have a Stored Procedure that uses a CURSOR.  How could this be changed to not use a CURSOR?

The attached is the test code for the Stored Procedure.
DeletePDQUsers.sql
0
Comment
Question by:wdbates
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 34

Accepted Solution

by:
ste5an earned 500 total points
ID: 41822243
Caveat: You can do it without CURSOR. But this means one batch and on transaction instead of one transaction per row in the cursor.

DECLARE @Sql NVARCHAR(MAX);
DECLARE @p_UserID INT = 0;

WITH    Data
          AS ( SELECT DISTINCT
                        PDQTableName
               FROM     sPDQDATA.LTrack L
                        INNER JOIN sPDQDATA.Ements E ON L.LTID = E.LTID
                                                        AND E.UserID = @p_UserID
               WHERE    PDQTableName IS NOT NULL
             )
    SELECT  @Sql = ( SELECT 'DELETE FROM sPDQData.' + QUOTENAME(PDQTableName)
                            + ' WHERE UserID = '
                            + CAST(@p_UserID AS VARCHAR(12)) + '; '
                     FROM   Data D
    FOR     XML PATH('') ,
                TYPE
 ).value('.', 'NVARCHAR(MAX)');    

PRINT @Sql;
--EXECUTE (@Sql);

Open in new window

0
 

Author Closing Comment

by:wdbates
ID: 41822273
Great work!
Thank you for the quick response.
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question