return: text
lang: plpgsql
parameters:
  p0:
    type: text
    name: i_from_table
  p1:
    type: text
    name: i_to_table
src: |
  DECLARE	
  	_sqlcmd TEXT;
  	result TEXT;
  BEGIN
  	IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = i_to_table) THEN
  		_sqlcmd = '
  		CREATE TEMP TABLE ' || i_to_table || '
  		(
  			XXCENT numeric,
  			XXCETS numeric,
  			XXCODO text,
  			XXCODE text,
  			in_code text,
  			in_code_original text,
  			in_texte text,
  			in_id bigint
  		);
  		CREATE INDEX ' || i_to_table || '_i1 ON ' || i_to_table || ' USING btree(XXCODO)
  		'
  		;
  		EXECUTE _sqlcmd;
  	END IF;
  	
  	
  	-- Table de correspondance
  	_sqlcmd = '
  	TRUNCATE ' || i_to_table || '
  	;
  	INSERT INTO ' || i_to_table || ' 
  	SELECT
  		XXCENT,
  		XXCETS,
  		XXCODO,
  		XXCODE,
  		XXCODE ||
  		CASE WHEN base.cti_soundex_nom(replace(XXTEXT,''.'','''')) <> XXTEXT_STD_soundex THEN
  			''('' || XXCENT || ''.'' || XXCETS || '')''
  		ELSE '''' END
  		 AS in_code,
  		XXCODO ||
  		CASE WHEN base.cti_soundex_nom(replace(XXTEXT,''.'','''')) <> XXTEXT_STD_soundex THEN
  			''_'' || to_char(XXCENT,''FM000'') || to_char(XXCETS,''FM000'')
  		ELSE ''''  END
  		 AS in_code_original,
  		CASE WHEN base.cti_soundex_nom(replace(XXTEXT,''.'','''')) <> XXTEXT_STD_soundex THEN XXTEXT ELSE XXTEXT_STD END AS in_texte,
  		0::bigint AS in_id
  	FROM
  		' || i_from_table || '
  		JOIN 
  			(
  				SELECT XXCODE AS XXCODE_STD, 
  					(MAX(Array[key, XXTEXT_soundex]))[2] AS XXTEXT_STD_soundex,
  					(MAX(Array[key, XXTEXT_STD]))[2] AS XXTEXT_STD
  				FROM
  				(
  				SELECT XXCODE, 
  					base.cti_soundex_nom(replace(XXTEXT,''.'','''')) AS XXTEXT_soundex, 
  					MIN(XXTEXT) AS XXTEXT_STD,
  					to_char(count(*),''FM0000000000'') || MIN(to_char(XXCENT,''FM000'') || to_char(XXCETS,''FM000'')) AS key
  				FROM ' || i_from_table || '
  				GROUP BY 1,2
  				) subview
  				GROUP BY 1
  			) cti_shs_multicode_std
  			ON XXCODE = XXCODE_STD
  	ORDER BY 3,5
  	;'
  	;
  	EXECUTE _sqlcmd;
  	
  	RETURN 'OK';
  END;