如何删除不同表中的多行?

时间:2018-04-25 06:31:15

标签: sql sql-server stored-procedures

我有一点问题,如何改进我的QUERY,我想使用外键从多个表中删除多行:

CREATE PROCEDURE SCOUTL.DeleteRegistroUsuario(@ID INT)
AS
     BEGIN
         DECLARE @Evidencia AS UNIQUEIDENTIFIER;
         SET @Evidencia =
(
    SELECT e.IdEvidenciaPorPractica
    FROM SCOUTL.EvidenciaPorPractica e
         INNER JOIN SCOUTL.RegistroUsuario r ON e.IdEvidenciaPorPractica = r.IdEvidenciaPorPracticaFK
    WHERE r.IdRegistroUsuario = @ID
);
         DELETE FROM SCOUTL.RegistroUsuario
         WHERE IdRegistroUsuario = @ID;
         DELETE FROM SCOUTL.EvidenciaPorPractica
         WHERE IdEvidenciaPorPractica = @Evidencia;
     END;

但是,当我执行此查询时,请返回:

  

Incorrect syntax near @ID

请,我需要更正

3 个答案:

答案 0 :(得分:1)

我们可以使用joinsdelete语句来执行此操作 -

CREATE PROCEDURE SCOUTL.DeleteRegistroUsuario(@ID INT)
AS
BEGIN
    DELETE e
    FROM SCOUTL.EvidenciaPorPractica e
    INNER JOIN SCOUTL.RegistroUsuario r ON
         e.IdEvidenciaPorPractica = r.IdEvidenciaPorPracticaFK
    WHERE r.IdRegistroUsuario = @ID

    DELETE FROM SCOUTL.RegistroUsuario
    WHERE IdRegistroUsuario = @ID
END;

如果要自动删除外键表数据,可以查看On Delete Cacade

答案 1 :(得分:0)

试试这个

CREATE PROCEDURE dbo.DeleteRegistroUsuario
(
    @ID INT
)
AS
BEGIN

    DELETE E
       FROM SCOUTL.EvidenciaPorPractica e
          INNER JOIN SCOUTL.RegistroUsuario r 
             ON e.IdEvidenciaPorPractica = r.IdEvidenciaPorPracticaFK
       WHERE r.IdRegistroUsuario = @ID

    DELETE FROM SCOUTL.RegistroUsuario WHERE IdRegistroUsuario = @ID;

END;

答案 2 :(得分:0)

试试这个:

 CREATE PROCEDURE SCOUTL.DeleteRegistroUsuario(@ID INT)
AS
BEGIN

    DELETE e FROM SCOUTL.EvidenciaPorPractica AS e
    INNER JOIN SCOUTL.RegistroUsuario r ON e.IdEvidenciaPorPractica = r.IdEvidenciaPorPracticaFK
    WHERE r.IdRegistroUsuario = @ID

    DELETE FROM SCOUTL.RegistroUsuario
    WHERE IdRegistroUsuario = @ID;

END;