 			     AND t.target_table = %L'
 			     ,ssname, stname,tsname, ttname)
     LOOP
-        insertfield := concat(insertfield, virgule, r.target_field);
-        selectfield := concat(selectfield, virgule, r.source_field,'::',r.target_field_type);
-        virgule := ', ';
+        insertfield := concat(insertfield, virgule, r.target_field, chr(10));
+        selectfield := concat(
+				selectfield, 
+				virgule, 
+				COALESCE('a.'||r.source_field, r.source_default_value),
+				'::',
+				r.target_field_type, 
+				' AS ', 
+				r.target_field,
+				chr(10));
+        virgule := ',';
     END LOOP;
     --gestion du geom avec la table gn_imports.matching_geoms
     FOR g IN EXECUTE format('SELECT g.* FROM gn_imports.matching_geoms g

        END LOOP;
    END IF;
    RETURN format('CREATE TABLE %I.%I FROM %L', sname, tname, csv_file);
end $$;

CREATE OR REPLACE FUNCTION fct_generate_import_query(
  mysource_table text, 
  mytarget_table text)  RETURNS text AS
--This function prépare a sql query to insert data from a table to another.
--Use the 3 matching tables in gn_imports schema.
--USAGE : gn_imports.fct_generate_import_query('table_source', 'table_cible');
$BODY$
DECLARE
    insertfield text; --prepared field to insert
    selectfield text; --prepared field in select clause

	END IF;
    END LOOP;
    --finalisation de la clause insert
    insertfield := concat(insertfield, ')', chr(10));
    selectfield := concat(selectfield, 'FROM ', ssname, '.', stname, ' a', chr(10));
    --construction de la requête complète
    sqlimport := concat(insertfield, ' ', selectfield, ';');
    RETURN sqlimport;
END $$;
