その関数のパラメーターに基づいて列のセットを返すために、次の関数を作成しました。
CREATE OR REPLACE FUNCTION getColumns(IN _column1 text, IN _column2 text, IN _column3 text, IN _column4 text, IN _table text)
RETURNS TABLE(cmf1 text, cmf2 text, cmf3 text, cmf4 text) AS
$BODY$
BEGIN
RETURN QUERY EXECUTE
'SELECT '
|| case when _column1 = 'None' then quote_literal('None') else quote_ident(_column1) end || '::text as cmf1,'
|| case when _column2 = 'None' then quote_literal('None') else quote_ident(_column2) end || '::text as cmf2,'
|| case when _column3 = 'None' then quote_literal('None') else quote_ident(_column3) end || '::text as cmf3,'
|| case when _column3 = 'None' then quote_literal('None') else quote_ident(_column3) end || '::text as cmf4'
' FROM '
|| _table;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
サンプルテーブルの使用:
CREATE TABLE test20130205
(
a text,
b text,
c character varying,
d text
);
この関数は次のように使用できます。
select * from getColumns('a','b','c','d','test20130205');
次の質問があります。
この関数を拡張して、入力として任意の数の列を取得するにはどうすればよいですか(現在は4つに制限されています)。
getColumns([textColumn1,...,textColumnN],'table')
現在、必要な列が4つ未満の場合に備えて、パラメーター値として「なし」を使用する必要がありますが、これを回避する方法はありますか?これは前の質問に答えることで自動的に解決されると思います
どういうわけか出力でデータ型を保持できますか?そうでない場合、より多くの配列パラメーターを使用できますか?この場合、関数は次のようになります。
getColumns( [textColumn1,...,textColumnN], [numericColumn1,...,numericColumnM], [dateColumn1,...,dateColumnO], [intColumn1,...,intColumnP], 'table' )