Last active
June 26, 2024 21:53
-
-
Save edgarronda/b192c18a4f791debceaf97b3d16e9975 to your computer and use it in GitHub Desktop.
insert_into_with_errors_for_SQL.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
----------------------------------------- | |
-- Creation error table. | |
----------------------------------------- | |
IF OBJECT_ID('dbo.TablaErrores', 'U') IS NULL | |
BEGIN | |
CREATE TABLE dbo.TablaErrores ( | |
id INT IDENTITY(1,1) PRIMARY KEY, | |
col1 INT, | |
col2 VARCHAR(255), | |
ErrorMensaje NVARCHAR(MAX), | |
FechaError DATETIME DEFAULT GETDATE() | |
-- Otras columnas según sea necesario | |
); | |
END; | |
----------------------------------------- | |
-- SP Creation | |
----------------------------------------- | |
CREATE PROCEDURE insertar_datos_y_capturar_errores | |
AS | |
BEGIN | |
DECLARE @col1 INT; | |
DECLARE @col2 VARCHAR(255); | |
-- Cursor para iterar sobre los datos de TablaOrigen | |
DECLARE datos_cursor CURSOR FOR | |
SELECT col1, col2 | |
FROM dbo.TablaOrigen; | |
OPEN datos_cursor; | |
FETCH NEXT FROM datos_cursor INTO @col1, @col2; | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
BEGIN TRY | |
-- Intentar insertar en TablaDestino | |
INSERT INTO dbo.TablaDestino (col1, col2) | |
VALUES (@col1, @col2); | |
END TRY | |
BEGIN CATCH | |
-- Capturar error y registrar en TablaErrores | |
INSERT INTO dbo.TablaErrores (col1, col2, ErrorMensaje) | |
VALUES (@col1, @col2, ERROR_MESSAGE()); | |
END CATCH; | |
FETCH NEXT FROM datos_cursor INTO @col1, @col2; | |
END; | |
CLOSE datos_cursor; | |
DEALLOCATE datos_cursor; | |
END; | |
------------------ | |
-- Calling the SP | |
------------------ | |
EXEC insertar_datos_y_capturar_errores; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment