These things are usually best left to the presentation layer however...
For the CustomerNumber to have the format you specified you will need more than
varchar(10)
for starters.
I used this table:
create table Customers
(
[dbID] int identity not null primary key,
CustomerName varchar(100),
CustomerNumber varchar(20)
)
I also created a table that will provide an offset for each year
create table StartYearDetails
(
YearEnd int,
MaxId int
)
And a Stored Procedure to manage the "closing year" process (this could obviously contain any other processing related to "closing off a year")
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE pCloseYear
(
@StartYear int
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @MaxId int = (SELECT MAX([dbID]) FROM Customers)
Insert into StartYearDetails values
(@StartYear, ISNULL(@MaxId,0))
END
GO
Essentially it is capturing the value of the last (automated) id allocated on the table. It takes the year as a parameter rather than using GetDate() as Year End procedures are usually run in the days following the actual physical end of year.
At the starting point running the stored procedure initialises the process e.g.
EXEC pCloseYear 2016
gives
2016 0
I then generated a TRIGGER for the Customers table
CREATE TRIGGER dbo.Customer_Insert
ON Customers
AFTER INSERT
AS
DECLARE @offset int
DECLARE @yearno int
SELECT TOP 1 @offset = MaxId, @yearno = YearEnd FROM StartYearDetails ORDER BY YearEnd DESC
UPDATE a
set CustomerNumber = 'MHSIC/' + CAST(@yearno as varchar) + '/E/' + REPLICATE('0', 6-LEN(cast(a.[dbID] as varchar))) + CAST(a.[dbID] - @offset as varchar)
from Customers a
INNER JOIN inserted b on a.[dbID]=b.[dbID]
GO
which queries the
StartYearDetails
table to work out the necessary offset to build up the derived
CustomerNumber
I then tested it all like this...
insert into Customers(CustomerName) values
('CUSTOMER1 2016'),
('CUSTOMER2 2016'),
('CUSTOMER3 2016'),
('CUSTOMER4 2016')
EXEC pCloseYear 2017
insert into Customers(CustomerName) values
('CUSTOMER5 2017'),
('CUSTOMER6 2017'),
('CUSTOMER7 2017'),
('CUSTOMER8 2017')
Results:
1 CUSTOMER1 2016 MHSIC/2016/E/000001
2 CUSTOMER2 2016 MHSIC/2016/E/000002
3 CUSTOMER3 2016 MHSIC/2016/E/000003
4 CUSTOMER4 2016 MHSIC/2016/E/000004
5 CUSTOMER5 2017 MHSIC/2017/E/000001
6 CUSTOMER6 2017 MHSIC/2017/E/000002
7 CUSTOMER7 2017 MHSIC/2017/E/000003
8 CUSTOMER8 2017 MHSIC/2017/E/000004