简体   繁体   中英

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

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

It may be helpful: UPDATE from SELECT using SQL Server

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM