Last active
June 26, 2024 20:26
-
-
Save edgarronda/8e89823c1e5c82036ac4ef3f662a2dc0 to your computer and use it in GitHub Desktop.
Inserción con Captura de Errores
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
-- Crear tabla temporal | |
CREATE TEMPORARY TABLE TempTable AS | |
SELECT col1, col2, ... | |
FROM TablaOrigen; | |
-- Intentar insertar y capturar errores | |
DO $$ | |
DECLARE | |
rec RECORD; | |
BEGIN | |
FOR rec IN SELECT * FROM TempTable LOOP | |
BEGIN | |
INSERT INTO TablaDestino (col1, col2, ...) | |
VALUES (rec.col1, rec.col2, ...); | |
EXCEPTION | |
WHEN OTHERS THEN | |
INSERT INTO TablaErrores (col1, col2, ErrorMensaje) | |
VALUES (rec.col1, rec.col2, SQLERRM); | |
END; | |
END LOOP; | |
END $$; | |
-------------------------------- | |
--- WITHOUT DO $$ (Ready to prod) | |
--- | |
--- How to call it? | |
--- CALL insertar_datos_y_capturar_errores(); | |
-------------------------------- | |
CREATE OR REPLACE FUNCTION insertar_datos_y_capturar_errores() | |
RETURNS VOID AS $$ | |
DECLARE | |
rec RECORD; | |
BEGIN | |
FOR rec IN SELECT * FROM TablaOrigen LOOP | |
BEGIN | |
-- Intentar insertar en TablaDestino | |
INSERT INTO TablaDestino (col1, col2) | |
VALUES (rec.col1, rec.col2); | |
EXCEPTION | |
WHEN OTHERS THEN | |
-- Si ocurre un error, registrar los datos problemáticos en TablaErrores | |
INSERT INTO TablaErrores (col1, col2, ErrorMensaje) | |
VALUES (rec.col1, rec.col2, SQLERRM); | |
END; | |
END LOOP; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment