IF OBJECT_ID('P_GRAVA_EST_PROD_COMPRADOR') IS NOT NULL
	BEGIN
		DROP PROCEDURE P_GRAVA_EST_PROD_COMPRADOR
	END
 
GO 

CREATE PROCEDURE P_GRAVA_EST_PROD_COMPRADOR
(
    @CD_EMP        INT,
    @CD_PROD       INT,
    @CD_COMPRADOR  INT,
    @CD_USU        INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @CD_CTR INT;

    BEGIN TRY
        BEGIN TRAN;

        IF EXISTS (
            SELECT 1
            FROM EST_PROD_COMPRADOR EPC
            INNER JOIN EST_PROD_COMPRADOR_CPL ECPL
                ON EPC.CD_CTR = ECPL.CD_CTR
            WHERE EPC.CD_EMP = @CD_EMP
              AND EPC.CD_COMPRADOR <> @CD_COMPRADOR
              AND ECPL.CD_PROD = @CD_PROD
        )
        BEGIN
            DELETE ECPL
            FROM EST_PROD_COMPRADOR_CPL ECPL
            WHERE ECPL.CD_EMP = @CD_EMP
              AND ECPL.CD_PROD = @CD_PROD;
        END

        SELECT @CD_CTR = CD_CTR
        FROM EST_PROD_COMPRADOR
        WHERE CD_EMP = @CD_EMP
          AND CD_COMPRADOR = @CD_COMPRADOR;

        IF @CD_CTR IS NULL
        BEGIN
            INSERT INTO EST_PROD_COMPRADOR
            (CD_EMP, CD_COMPRADOR, DT_CAD, CD_USU)
            VALUES
            (@CD_EMP, @CD_COMPRADOR, GETDATE(), @CD_USU);

            SET @CD_CTR = SCOPE_IDENTITY();
        END
        ELSE
        BEGIN
            DELETE FROM EST_PROD_COMPRADOR_CPL
            WHERE CD_EMP = @CD_EMP
              AND CD_PROD = @CD_PROD;
        END

        INSERT INTO EST_PROD_COMPRADOR_CPL
        (CD_CTR, CD_EMP, CD_PROD, DT_CAD)
        VALUES
        (@CD_CTR, @CD_EMP, @CD_PROD, GETDATE());

        COMMIT TRAN;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRAN;

        THROW;
    END CATCH
END
GO