通过一次调用删除sp中多行的有效方法

时间:2011-12-27 22:10:43

标签: sql sql-server-2008

以下查询返回两行:

SELECT 
DocList.DocListId, RegistrationDocList.RegistrationDocListId, Registration.RegistrationId 
FROM 
DocList INNER JOIN
RegistrationDocList ON DocList.DocListId = RegistrationDocList.DocListId INNER JOIN
Registration ON RegistrationDocList.RegistrationId = Registration.RegistrationId
WHERE (DocList.DocListId = 547)

结果:

--------------------------------------------------------
DocListId   RegistrationDocListId    RegistrationId
-------------------------------------------------------
547              097                     115
547              098                     116

更新:

因为你可以看到它使用三个表,所以我想删除以下行:

DocList where doclistid = 547
RegistrationDocList.RegistrationId  where RegistrationId in (097,098)
Registration.RegistrationId  where RegistrationId in (115,116)

2 个答案:

答案 0 :(得分:1)

也许我错过了你的观点。我希望这段代码可以帮到你:

DECLARE @Result int

BEGIN TRAN
    BEGIN TRY
        DELETE DocList where doclistid = 547
        DELETE RegistrationDocListwhere RegistrationId in (097,098)
        DELETE Registration where RegistrationId in (115,116)

        /* code was done properly => mark flag as OK */
        SET @Result = 0
    END TRY
    BEGIN CATCH
        /* some error occured => mark flag as ERROR */
        SET @Result = -1
    END CATCH

IF @Result = 0 BEGIN
    /* all is fine, transaction can be commited */
    COMMIT TRAN
END
ELSE BEGIN
    /* something is wrong, transaction must be rolled back */
    ROLLBACK TRAN
END

答案 1 :(得分:0)

您需要在链接表的远端缓存要删除的值,删除链接记录,然后删除链接的记录:

DECLARE @reg_to_delete TABLE (id int)

INSERT INTO @reg_to_delete (id)
SELECT RegistrationID FROM RegistrationDocList WHERE DocListID = 547

DELETE FROM RegistrationDocList WHERE DocListID = 547

DELETE FROM RegistrationList WHERE RegistrationID IN (SELECT id FROM @reg_to_delete)

DELETE FROM DocList WHERE DocListID = 547