Last active
June 18, 2019 12:27
-
-
Save mdouchin/50234f1f33801aed6f4f2cbab9f4887c to your computer and use it in GitHub Desktop.
POSTGIS - Function to add multiple fields to a given table
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
-- Fonction de création des champs nécessaires sur les tables | |
-- DROP FUNCTION IF EXISTS public.ajout_champs_dynamiques(text, text, text); | |
CREATE OR REPLACE FUNCTION public.ajout_champs_dynamiques(schemaname text, tablename text, colonnes text) | |
RETURNS INTEGER AS | |
$limite$ | |
DECLARE | |
colonnes_a text[]; | |
sql_text text; | |
t text; | |
BEGIN | |
colonnes_a = regexp_split_to_array(colonnes, ','); | |
FOREACH t IN ARRAY colonnes_a LOOP | |
BEGIN | |
sql_text = 'ALTER TABLE ' || quote_ident(schemaname) || '.' || quote_ident(tablename) || ' ADD COLUMN ' || t; | |
EXECUTE sql_text; | |
RAISE NOTICE 'Colonne % créée', t; | |
EXCEPTION WHEN OTHERS THEN | |
RAISE NOTICE 'ERREUR - Colonne % non créée', t; | |
RAISE NOTICE '%', sql_text; | |
END; | |
END LOOP; | |
RETURN 1; | |
END; | |
$limite$ | |
LANGUAGE plpgsql | |
; | |
-- Lancer la création de champs sur toutes les tables | |
-- du schéma test | |
-- contenant des géométries de type Point | |
SELECT f_table_schema, f_table_name, | |
ajout_champs_dynamiques( | |
-- schéma | |
f_table_schema, | |
-- table | |
f_table_name, | |
-- liste des champs, au format nom_du_champ TYPE | |
'un_champ_texte text, un_champ_reel_tres_precis double precision, un_reel real, un_entier integer' | |
) | |
FROM geometry_columns | |
WHERE True | |
AND "type" LIKE '%POINT' | |
AND f_table_schema IN ('test') | |
ORDER BY f_table_schema, f_table_name | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment