0

How to update 1 column in a temp table based on an EXISTS in a sub-query?

I am using SQL Server 2008 R2 and there are about 3000 rows.. so I need it to be fast

This works.. but I don't know where to go from here..

SELECT ROW_NUMBER() OVER(ORDER BY RowID) AS RowNumber 
FROM #tempTable

How would I update 1 column in this #tempTable based on another subquery that is actually also 2 joined tables?

Does what I have shown here with ROW_NUMBER belong in the WHERE clause?

I am trying to eliminate a WHILE loop in an existing stored procedure and I have never worked with ROW_NUMBER

Existing Procedure:

   DECLARE @StopRow AS INT

    SELECT @StopRow = MAX(RowID)
    FROM #Temp1

    DECLARE @RowCounter AS INT

    SET @RowCounter = 1

    DECLARE @colID INT

    WHILE (@RowCounter <= @StopRow)
    BEGIN
        SELECT @colID = colID
        FROM #Temp1
        WHERE colRowID = @RowCounter

        IF (
                EXISTS (
                    SELECT ParentColID
                    FROM ParentTable a WITH (NOLOCK)
                    JOIN MoreTableData b WITH (NOLOCK) ON a.priID = b.priID
                        AND colID = @colID
                    WHERE anotherID NOT IN (
                            SELECT anotherID
                            FROM @anotherTempTable
                            )
                    )
                )
            UPDATE #Temp1
            SET aFlag = 0
            WHERE colRowID = @RowCounter

        SET @RowCounter = @RowCounter + 1
    END
Ivan Chaer
  • 6,980
  • 1
  • 38
  • 48
JoJo
  • 4,643
  • 9
  • 42
  • 65

2 Answers2

1

It may be helpful: UPDATE from SELECT using SQL Server

So, you can use custom expressions for bulk UPDATE of the records

Community
  • 1
  • 1
Ivan Surzhenko
  • 149
  • 1
  • 8
0

It seems that your query in correct but may be there is some formatting issue.

Try this changed query.

DECLARE @StopRow AS INT

SELECT @StopRow = MAX(RowID)
FROM #Temp1

DECLARE @RowCounter AS INT

SET @RowCounter = 1

DECLARE @colID INT

WHILE (@RowCounter <= @StopRow)
BEGIN
    SELECT @colID = colID
    FROM #Temp1
    WHERE colRowID = @RowCounter

    IF  EXISTS (
                SELECT ParentColID
                FROM ParentTable a WITH (NOLOCK)
                JOIN MoreTableData b WITH (NOLOCK) ON a.priID = b.priID
                    AND colID = @colID
                WHERE anotherID NOT IN (
                        SELECT anotherID
                        FROM @anotherTempTable
                        )
            )

   BEGIN
        UPDATE #Temp1
        SET aFlag = 0
        WHERE colRowID = @RowCounter
   END

    SET @RowCounter = @RowCounter + 1
END
Alisworld
  • 1
  • 1