CREATE OR REPLACE FUNCTION sp_generateidforentity
(
	"EntName" varchar(256)
,	"FieldName" varchar(256) DEFAULT 'PrimaryKey'::varchar(256)
,	"count" integer DEFAULT 1
)
RETURNS integer AS
$BODY$
Declare	_rc int;
	_msg text;
Begin
	_msg := 'Ошибка генерации id для ' || "EntName";

	--LOCK TABLE T_ENTITY_IDS IN ACCESS EXCLUSIVE MODE;
	select id 
	from T_ENTITY_IDS
	into _rc 
	where EntName = "EntName" 
	and FieldName = "FieldName"
	for update;

	if _rc is null  
	then  
		insert into T_ENTITY_IDS(id, EntName, FieldName) 
		values(1 + "count", "EntName", "FieldName");
		_rc := 1;
	else   
		update T_ENTITY_IDS 
		set id = id + "count" 
		where EntName = "EntName" 
		and FieldName = "FieldName";
	end if;
	return _rc;
Exception
	WHEN Others 
	THEN Raise Exception Using Message = _msg;
Return -1;
End;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION sp_generateidforentity(character varying, character varying, integer)
  OWNER TO postgres;
