Certainly! To achieve synchronization between your two databases—LD_INTERFACE_GRFP and LDCOM_GRFP_DEV—you want to not only update and insert new or modified rows into Articulo_Grupo but also delete any rows in LD_INTERFACE_GRFP.dbo.Articulo_Grupo that have been removed from LDCOM_GRFP_DEV.dbo.Articulo_Grupo.
Below is the modified stored procedure with the necessary changes to handle deletions:
USE [LD_INTERFACE_GRFP]
GO
/****** Object: StoredProcedure [dbo].[Articulo_Grupo_Actualizar] Script Date: 14/11/2024 06:03:08 p. m. ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Articulo_Grupo_Actualizar 2
ALTER PROC [dbo].[Articulo_Grupo_Actualizar]
(@Tipo SMALLINT) -- (1 - Delta / 2 - Completa)
AS
BEGIN
SET NOCOUNT ON;
DECLARE
@msg VARCHAR(255),
@Msg_id INT,
@Fecha DATETIME;
BEGIN TRY
-- Determine the cutoff date based on @Tipo
IF @Tipo = 1
SET @Fecha = DATEADD(DAY, -1, GETDATE());
ELSE
SET @Fecha = '1900-01-01';
-- Step 1: Select updated or new rows from the source database
SELECT *
INTO #Articulo_Grupo
FROM LDCOM_GRFP_DEV.dbo.Articulo_Grupo
WHERE Grupo_Fec_Actualizacion > @Fecha;
-- Step 2: Delete existing rows in the target that are present in the updated set
DELETE A
FROM Articulo_Grupo A
WHERE EXISTS (
SELECT 1
FROM #Articulo_Grupo B
WHERE A.Emp_Id = B.Emp_Id
AND A.Grupo_Id = B.Grupo_Id
);
-- Step 3: Insert the updated/new rows into the target
INSERT INTO Articulo_Grupo (
Emp_Id,
Grupo_Id,
Grupo_Nombre,
Grupo_Fec_Actualizacion,
Usuario_Id,
Grupo_Estado
)
SELECT
Emp_Id,
Grupo_Id,
Grupo_Nombre,
Grupo_Fec_Actualizacion,
Usuario_Id,
Grupo_Estado
FROM #Articulo_Grupo;
-- Step 4: **Delete rows from target that do not exist in the source**
DELETE A
FROM Articulo_Grupo A
LEFT JOIN LDCOM_GRFP_DEV.dbo.Articulo_Grupo B
ON A.Emp_Id = B.Emp_Id
AND A.Grupo_Id = B.Grupo_Id
WHERE B.Emp_Id IS NULL
AND B.Grupo_Id IS NULL
-- Optional: Add additional conditions if needed
;
-- Clean up temporary table
DROP TABLE #Articulo_Grupo;
END TRY
BEGIN CATCH
-- Error handling
SET @msg = ERROR_MESSAGE();
SELECT @Msg_id = ISNULL(MAX(MSG_id), 0) + 1
FROM msg_message
WHERE Emp_id = 1
AND Suc_id = 0
AND Caja_id = 0
AND modulo_id = 0;
INSERT INTO Msg_Message (
Emp_id,
Suc_id,
Caja_id,
Modulo_id,
Msg_id,
Msg_Fecha,
Msg_Codigo,
Msg_Descripcion,
Msg_Descripcion_Full
)
SELECT
1, 0, 0, 0,
@Msg_id, GETDATE(), 4000004,
'Error Articulo_Grupo_Actualizar', @msg;
RETURN 1;
END CATCH
END
Explanation of Changes:
-
Added Step 4: Deletion of Removed Rows
After inserting the updated and new rows from the source database into LD_INTERFACE_GRFP.dbo.Articulo_Grupo, we need to ensure that any rows no longer present in the source (LDCOM_GRFP_DEV.dbo.Articulo_Grupo) are also removed from the target. This is accomplished by performing a LEFT JOIN between the target and source tables and deleting any rows in the target that do not have a corresponding match in the source.
DELETE A
FROM Articulo_Grupo A
LEFT JOIN LDCOM_GRFP_DEV.dbo.Articulo_Grupo B
ON A.Emp_Id = B.Emp_Id
AND A.Grupo_Id = B.Grupo_Id
WHERE B.Emp_Id IS NULL
AND B.Grupo_Id IS NULL;
- LEFT JOIN ensures that all records from
Articulo_Grupo in LD_INTERFACE_GRFP are returned along with matching records from LDCOM_GRFP_DEV.dbo.Articulo_Grupo.
- WHERE B.Emp_Id IS NULL AND B.Grupo_Id IS NULL identifies records in the target that have no corresponding record in the source, indicating they have been removed from the source and should be deleted from the target.
-
Improved Date Calculation
Replaced Getdate() - 1 with DATEADD(DAY, -1, GETDATE()) for better readability and to follow SQL Server best practices.
-
Added SET NOCOUNT ON
Prevents the sending of DONE_IN_PROC messages to the client for each statement, which can improve performance.
-
Clean Up Temporary Table
Ensures that the temporary table #Articulo_Grupo is dropped after its usage to free up resources.
DROP TABLE #Articulo_Grupo;
-
Consistent Naming and Formatting
Improved the readability of the code by aligning keywords and properly indenting the SQL statements.
Additional Recommendations:
-
Transaction Handling: Depending on your requirements, you might want to encapsulate the entire procedure within a transaction to ensure atomicity. This way, if any part of the synchronization fails, the entire operation can be rolled back to maintain data integrity.
BEGIN TRY
BEGIN TRANSACTION;
-- [Your synchronization steps here]
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
-- [Error handling here]
END CATCH;
-
Performance Considerations: Ensure that the Emp_Id and Grupo_Id columns are properly indexed in both tables to optimize the JOIN and WHERE operations, especially if the tables are large.
-
Logging and Monitoring: Depending on how critical this synchronization is, consider adding more detailed logging or monitoring to track successes and failures over time.
Final Notes:
This modified stored procedure will now synchronize the Articulo_Grupo table between the two databases by:
- Updating/Inserting new or changed rows based on the
Grupo_Fec_Actualizacion.
- Deleting any rows in
LD_INTERFACE_GRFP.dbo.Articulo_Grupo that have been removed from LDCOM_GRFP_DEV.dbo.Articulo_Grupo.
Ensure you test this procedure in a development environment before deploying it to production to verify that it behaves as expected and doesn't unintentionally delete important data.