DROP PROCEDURE IF EXISTS vclib.sp_generatenumber;
DROP FUNCTION IF EXISTS vclib.sp_generatenumber;
-- =============================================
-- Author:  (C) Vitacard System 2009
-- Create date: 2009-08-05
-- Description: Генерирует номер
-- =============================================
CREATE PROCEDURE vclib.sp_generatenumber
(
	"EntityID" integer
,	"NumberName" varchar(64)
,	"count" integer DEFAULT 1
,   INOUT _val integer DEFAULT -1
)
LANGUAGE plpgsql AS
$proc$
Declare	_msg text;
BEGIN
	_msg := 'Ошибка генерации номера.';

	select t.NextNumber 
	from vclib.T_GEN_NUMBERS t
	into _val
	where t.EntityID = "EntityID" 
	and t.NumberName like "NumberName"
	for update;
	
	if _val is null 
	then
		_val := 1;
		insert into vclib.T_GEN_NUMBERS (GenNumbersID, EntityID, NumberName, NextNumber) 
		select gen_random_uuid(), "EntityID", "NumberName", _val + "count" - 1;
	else
		_val := _val + 1;
		update vclib.T_GEN_NUMBERS 
		set NextNumber = _val + "count" - 1 
		where EntityID = "EntityID"
		and NumberName = "NumberName";
	end if;
	return;
Exception
	WHEN Others 
	THEN Raise Exception Using Message = _msg;
	_val := -1;
return;
End
$proc$;