Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

CURSOR vs. CTE

$
0
0

Good morning and a happy Monday to all.

My mind is currently dribbling out of my ears and making a mess on my desk as I look at a cursor that I'm trying to optimize.

My thought is that I should replace it witha CTE expression, but I'm not familiar enough with SQL to know if, 1. I am correct and, 2. I'm doing it right.

So, I thought I'd post the cursor and the CTE replacement and see if anyone had any thoughts.

Here's the cursor;

DECLARE curDup CURSOR FOR
  SELECT
    sh1.KeyID,
    dp.KeyID AS KeyIDUpdate
  FROM
    SHStaging1 AS sh1
    INNER JOIN #Dup3 AS dp
      ON sh1.[Combined Name] = dp.[Combined Name]
  WHERE
    sh1.KeyID <> dp.KeyID
  ORDER BY
    sh1.CaseID

  DECLARE @KeyID INT, @KeyIDUpdate INT

  OPEN curDup
    FETCH NEXT FROM curDup INTO  @KeyID, @KeyIDUpdate
    WHILE @@FETCH_STATUS = 0
      BEGIN
        UPDATE sh1
          SET
            Prim = COALESCE(sh1.Prim, '') + ';' + COALESCE(sh2.Prim, '')
          FROM
            SHStaging1 AS sh1,
            SHStaging1 AS sh2
          WHERE
            sh1.KeyID = @KeyIDUpdate
            AND sh2.KeyID = @KeyID

        FETCH NEXT FROM curDup INTO @KeyID, @KeyIDUpdate
      END

  CLOSE curDup
DEALLOCATE curDup

And, here's the CTE;

WITH curDup AS
  (
  SELECT
    sh1.KeyID,
    dp.KeyID AS KeyIDUpdate
  FROM
    SHStaging1 AS sh1
    INNER JOIN #Dup3 AS dp
      ON sh1.[Combined Name] = dp.[Combined Name] 
  WHERE
    sh1.KeyID <> dp.KeyID
  ORDER BY
    sh1.CaseID
  )
UPDATE sh1
  SET
    Prim = COALESCE(sh1.Prim, '') + ';' + COALESCE(sh2.Prim, '')
  FROM
    SHStaging1 AS sh1
    INNER JOIN curDup
      ON sh1.KeyID = curDup.KeyID,
    SHStaging1 AS sh2
    INNER JOIN curDup
      ON sh2.KeyID = curDup.KeyID
  WHERE
    sh1.KeyID = @KeyIDUpdate
    AND sh2.KeyID = @KeyID;

Am I on the right track? Or, is everyone laughing too much for me to ask so soon?

Any help or questions happily accepted!

Thanx!


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>