SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_GenerateIdForEntity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_GenerateIdForEntity]
GO
-- =============================================
-- Author:		Vitacore (C)
-- Create date: 2008-01-01
-- Description:	Генерирует идентификатор
-- =============================================
CREATE  PROCEDURE [dbo].[sp_GenerateIdForEntity]   
@EntName varchar(256),  
@FieldName varchar(256) = 'PrimaryKey',  
@count int = 1  
as  
BEGIN 
	declare @trancount int  
	declare @rc int  
	set @rc = null  
  
	set nocount on   
	select @trancount = @@trancount  
	if @trancount = 0 begin tran  
  
	set @rc = (select id from T_ENTITY_IDS with(rowlock,xlock) where EntName = @EntName and FieldName = @FieldName)  
  
	if @rc is null  
	begin  
	 insert T_ENTITY_IDS (id, EntName, FieldName) values(1+@count, @EntName, @FieldName)  
	 if @@error <> 0 goto err1  
	 set @rc = 1;  
	end   
	else  
	begin  
	 update T_ENTITY_IDS set id = id + @count where EntName = @EntName and FieldName = @FieldName  
	 if @@error <> 0 goto err1  
	end  
  
	if @trancount = 0 commit tran  

	select @rc  
	return
  
	err1:  
		if @trancount = 0 rollback tran  
		declare @msg as varchar(512)  
		set @msg = 'Ошибка генерации id для '+ @EntName  
		raiserror (@msg, 18, 1)
END
GO


