2013-02-28 147 views
0

我希望刪除結果select語句返回,原因我這樣做是因爲我有表之間的關係,如果我從最頂級的表中刪除其子表中的子行也被刪除。SQL Server存儲過程刪除語句

任何人都可以爲我糾正這個存儲過程嗎?

ALTER proc [dbo].[storedprocname] 
    (@Parameter uniqueidentifier = '00000000-0000-0000-0000-000000000000') 
AS BEGIN 
    DELETE FROM TableOne 
    WHERE IDOne IN 
     (SELECT 
      IDOne, 
      DescOne, IndexOne, 
      IDTwo, 
      QuestionTwo, ControlTypeTwo, IndexTwo, 
      IDThree, 
      DescThree, IndexThree, 
      QuestionFour, 
      OptionFour 
    FROM 
      TableOne 
     INNER JOIN 
      TableTwo ON TableTwo.CatID = TableOne.IDOne 
     INNER JOIN 
      TableThree ON TableThree.Question = TableTwo.IDTwo 
     LEFT OUTER JOIN 
      TableFour ON TableFour.Question = TableThree.IDThree 
     WHERE 
      TableOne.IDOne = @Parameter) 
END 

回答

1
ALTER proc [dbo].[storedprocname] 
    (@Parameter uniqueidentifier = '00000000-0000-0000-0000-000000000000') 
AS BEGIN 
    DELETE FROM TableOne 
    WHERE IDOne IN 
     (SELECT 
     IDOne 
     FROM 
     TableOne 
     INNER JOIN 
     TableTwo ON TableTwo.CatID = TableOne.IDOne 
     INNER JOIN 
     TableThree ON TableThree.Question = TableTwo.IDTwo 
     LEFT OUTER JOIN 
     TableFour ON TableFour.Question = TableThree.IDThree 
     WHERE 
     TableOne.IDOne = @Parameter) 
END 
1

既然要刪除所有行IDOne是可能的值的列表 - 那麼你需要確保子查詢後IN (...)也返回單列可以用於比較!畢竟,你不能在一個IDOne值進行比較,以你目前正在返回列的整個列表....

嘗試是這樣的:

ALTER proc [dbo].[storedprocname] 
    (@Parameter uniqueidentifier = '00000000-0000-0000-0000-000000000000') 
AS BEGIN 
    DELETE FROM TableOne 
    WHERE IDOne IN 
     (SELECT 
      IDOne 
     FROM 
      TableOne 
     INNER JOIN 
      TableTwo ON TableTwo.CatID = TableOne.IDOne 
     INNER JOIN 
      TableThree ON TableThree.Question = TableTwo.IDTwo 
     LEFT OUTER JOIN 
      TableFour ON TableFour.Question = TableThree.IDThree 
     WHERE 
      TableOne.IDOne = @Parameter) 
END 

我不知道(你的問題太模糊,不夠清楚)是否真的需要所有那些JOIN在子查詢中....你可能需要根據你的需求調整它。