SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_GenerateNumber]') and xtype = N'P')
drop procedure [dbo].[sp_GenerateNumber]
GO


-- =============================================
-- Author:		(C) Vitacard System 2009
-- Create date: 2009-08-05
-- Description:	Генерирует номер
-- =============================================
CREATE PROCEDURE [dbo].[sp_GenerateNumber]
	@EntityID int,
	@NumberName varchar(64),
	@count int = 1  
AS 
BEGIN 
	declare @trancount int 
	declare @NextNumber int 

	declare @msg as varchar(64) 

	set @NextNumber = null 

	set nocount on  
	select @trancount = @@trancount 
	if @trancount = 0 begin tran 
	 
	select @NextNumber = NextNumber from [AKUZ].T_GEN_NUMBERS with(rowlock,xlock) where EntityID = @EntityID and NumberName = @NumberName 
	 
	if @NextNumber is null 
		begin
		 set @NextNumber = 1
		 insert into [AKUZ].T_GEN_NUMBERS (GenNumbersID, EntityID, NumberName, NextNumber) values (newid(), @EntityID, @NumberName, @NextNumber+@count-1)
		 if @@error <> 0 goto err1
		end
	else
		begin 
		 set @NextNumber = @NextNumber + 1
		 update [AKUZ].T_GEN_NUMBERS set NextNumber = @NextNumber+@count-1 where EntityID = @EntityID and NumberName = @NumberName 
		 if @@error <> 0 goto err1 
		end 

	if @trancount = 0 commit tran 
	select @NextNumber
	return @NextNumber
	 
	err1: 
	if @trancount = 0 rollback tran 
	set @msg = 'Ошибка генерации номера.' 
	raiserror (@msg, 18, 1)
	select -1
	return
END
GO