2011-11-23 78 views
3

我在SQL刪除時遇到了一些麻煩。 SQL Server不喜歡在where子句中有多個參數從table_02刪除行(子查詢是表1)。任何幫助,將不勝感激。SQL Server - 使用子查詢幫助刪除具有多個where子句的行

謝謝。

DELETE FROM table_02 
     WHERE (col_1,col_2,col_3,col_4) 
     IN (   
      SELECT col_1,col_2,col_3,col_4 
        FROM table_01 
        GROUP BY 
        col_1,col_2,col_3,col_4 
        HAVING SUM(CASE WHEN col_1<6 THEN col_2*-1 ELSE col_2 END)=0 
      ) 

回答

5

可以重寫IN作爲EXISTS

DELETE 
FROM table_02 
WHERE EXISTS(SELECT * 
       FROM table_01 
       WHERE table_02.col_1 = table_01.col_1 
        AND table_02.col_2 = table_01.col_2 
        AND table_02.col_3 = table_01.col_3 
        AND table_02.col_4 = table_01.col_4 
       HAVING SUM(CASE 
          WHEN col_1 < 6 THEN col_2 * -1 
          ELSE col_2 
         END) = 0) 
1
Delete a 
from table1 a 
Inner Join table2 b 
on a.col = b.col 
WHERE ...