2014-06-19 57 views
0

如何根據子查詢中的EXISTS更新臨時表中的1列?如何根據子查詢中的EXISTS更新臨時表中的1列?

我使用SQL Server 2008 R2和大約有3000行..所以我需要它要快

這工作..但我不知道在哪裏可以從這裏去..

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

如何基於另一個實際上也是2個連接表的子查詢來更新此#tempTable中的1列?

我在這裏顯示的ROW_NUMBER屬於WHERE條款嗎?

我試圖消除現有的存儲過程WHILE循環,我從來沒有與ROW_NUMBER

現有過程的工作:

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 

回答

0

看來你的查詢正確但可能會有一些格式問題。

試試這個改變了的查詢。

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