question

Nikola7i avatar image
Nikola7i asked

Problem ms sql MAX() function in trigger

I have problem with this trigger,

when more user make insert rows on same condition MAX function somehow skip numbers .

For example

ROW 1 = BROJDOKUGOD = 1

ROW 2 = BROJDOKUGOD = 2

ROW 3 = BROJDOKUGOD = 5

the

BROJDOKUGOD 3 and 4 are missing , but only when min 3 user are inserting ...

GO
/****** Object:  Trigger [dbo].[AN]    Script Date: 27.8.2019. 10:10:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[AN] ON [dbo].[tDokument] 
FOR INSERT,UPDATE
AS

begin
declare @SifraDok int
declare @Godina int
declare @SifraPoduzeca int
declare @SifraOrgJed int
declare @Oznaka_dokumenta nvarchar
declare @BrojDokUGod int
declare @SifraVrste int
declare @BrojDokUGod_old int

IF (@@rowcount = 0) RETURN;

select @SifraDok=SifraDok, @SifraPoduzeca=SifraPoduzeca, @Godina = Godina, 
       @SifraOrgJed = SifraOrgJed,  @Oznaka_dokumenta = Oznaka_dokumenta,@SifraVrste = SifraVrste, @BrojDokUGod_old = BrojDokUGod
from   inserted


if @BrojDokUGod_old > 0
begin
	if exists(select 1 from tDokument where  @Godina = Godina and @SifraDok <> SifraDok and BrojDokUGod =@BrojDokUGod_old and SifraVrste = @SifraVrste AND Oznaka_Dokumenta = @Oznaka_dokumenta and  SifraOrgJed = @SifraOrgJed )
	begin
		RAISERROR ('Greška!!Već postoji taj broj dokumenta', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	end 
end
else
begin
	
	IF @Godina > 0 AND @SifraOrgJed > 0 AND @Oznaka_dokumenta <>'' AND @SifraVrste > 0
	BEGIN


		select @BrojDokUGod = isnull(max(BrojDokUGod)+1, 1)
		from dbo.tDokument
		where @Godina = Godina   
		and @SifraOrgJed = SifraOrgJed 
		and @Oznaka_Dokumenta = Oznaka_dokumenta 
		and @SifraVrste = SifraVrste

		update dbo.tDokument
		set odobrenje_fin = 1 ,proknjizena=0
		where SifraDok =  @SifraDok AND ( BrojDOkUGod = 0 or  BrojDOkUGod IS NULL) and oznaka_Dokumenta ='T' and tdokument.proknjizena = 0 --isnull(tdokument.proknjizena,0)

		update dbo.tDokument
		set       BrojDokUGod =@BrojDokUGod
		where  SifraDok =  @SifraDok  
				and ( BrojDokUGod  = 0 Or BrojDokUGod is null) 
				and   @Godina = Godina and SifraVrste = @SifraVrste AND Oznaka_Dokumenta = @Oznaka_dokumenta and  SifraOrgJed = @SifraOrgJed
				and ( SifraVrste <> 0 ) 
				and ( @BrojDokUGod > 0 or @BrojDokUGod is not null) 
				and ( @BrojDokUGod_old = 0 or @BrojDokUGod_old is null)


	END


		
	
end


end

max
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

0 Answers

·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.