【PostgreSQL】カンマ区切り文字列の指定カンマ箇所を取得する

PostgreSQL自作関数

説明

カンマ区切り文字列の、指定したカンマ箇所を取得する

例: 'abc,def,ghi'のカンマ区切り2番目の文字を取得→"def"

 

引数

引数1(character varying):対象の文字列

引数2(integer):何番目のカンマ位置を取得するか

 

返り値

指定したカンマ位置の文字列

 

コード

CREATE OR REPLACE FUNCTION get_comma_char(
    character varying,
    integer)
  RETURNS character varying AS
$BODY$
declare

	c_target		    alias for $1; --引数1:対象の文字列
	i_target_index		alias for $2; --引数2:何番目のカンマ位置を取得するか

	i_loopcount             integer;
	i_commacount            integer;
	i_charposition          integer;
	i_charlength            integer;

begin

	i_commacount = 0;
	i_charposition = 1;
	i_charlength = 0;

	for i_loopcount in 1..length(c_target) loop
		if substring(c_target, i_loopcount, 1) = ',' then
			i_commacount = i_commacount + 1;

			if i_commacount = i_target_index then
				--指定箇所でループを抜ける
				exit;
			end if;

			i_charposition = i_charposition + i_charlength + 1;
			i_charlength = 0;

		else
			i_charlength = i_charlength + 1;
		end if;

	end loop;

	--コンマがないときnullで返す
	if i_commacount = 0 then
	return null;
	end if;

	return substring(c_target, i_charposition, i_charlength);
	
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION get_comma_char(character varying, integer)
  OWNER TO postgres;

※PostgreSQL12で動作確認済み

 

実行例

select * From get_comma_char('abc,def,ghi,jkl,mn',4);
--jkl

 

他にもこんな関数があります(文字列操作の関数)

2つの文字列を比較して一致するかチェックする

文字列をバイト数で計算する

ひらがなをカタカナに置換する

文字を左のX文字目から○文字切り取る(Mid関数)

文字列中に指定した文字が含まれるかのチェック