I try to store a last document number for each deparment in a table
CREATE TABLE [LastDoc] (
[Department] [int] NOT NULL ,
[LastNum] [int] NULL CONSTRAINT [DF_LastDoc_LastNum] DEFAULT (0),
CONSTRAINT [PK_LastDoc] PRIMARY KEY CLUSTERED
(
[Deparment]
 
ON [PRIMARY]
) ON [PRIMARY]
GO
I create a store procedure to update the last number, This is a simplex example of my procedure