I’m using Entity Framework and MSSQL…
I need to insert a custom reference number when a record is inserted. The format is YYYY-01, YYYY-02, etc but the sequential number needs to be reset when a new year begins.
For example 2011-01, 2011-02, 2012-01
I’m curious if I should just go with a trigger or manage this with EF or ?
Having the sequential numbering reset each year has me a little confused…
Thanks for any advice!
Update:
Sorry, couldn’t get the Code tag to work well with the markup
--Variables
DECLARE @year INT,
@seqNum INT;
--Try to find if the [ComplaintCount] table already contains the current year
SET @year = (SELECT [Count_Year]
FROM [ComplaintCount]
WHERE [Count_Year] = YEAR(Getdate()))
--If the current year cannot be found in the [ComplaintCount] table, a new record for the current year needs to be made
IF @year IS NULL
BEGIN
--Get the Current Year and set the initial sequence number to start counting for the new year
SET @year = YEAR(Getdate());
SET @seqNum = 1;
--Insert the new default values into the [ComplaintCount] table
INSERT INTO [ComplaintCount]
(count_year,
count_current)
VALUES (@year,
@seqNum);
END
ELSE
BEGIN
--We found a record already in the [ComplaintCount] table for the current year
--Get the sequence number and increase it by one
SET @seqNum = (SELECT [Count_Current]
FROM [ComplaintCount]
WHERE [Count_Year] = @year) + 1
--Insert the new values into the [ComplaintCount] table
UPDATE [ComplaintCount]
SET [Count_Current] = @seqNum
WHERE [Count_Year] = @year;
END
--Its now safe to insert the correct reference number into the [Complaint] table
UPDATE
UPDATE [Complaint]
SET [Complaint_Reference] = CAST(@year AS VARCHAR) + ‘-‘ + CAST(
@seqNum AS VARCHAR)
FROM [Complaint]
INNER JOIN inserted
ON [Complaint].[PK_Complaint_Id] = inserted.[PK_Complaint_Id]
I’d say a trigger. Create a two column table that stores the year and the current record number and then uses a trigger to look up the current year, increment the count column by one, then return that count to the trigger. Build logic into the trigger that if the new year doesn’t exist, insert the new year record. I know most people like to avoid triggers if possible but that’s a pretty legit use of a trigger and way less processing than trying to count records on every insert.
Having a single row for every year and it’s related count may also prove useful in the future when you’re trying to audit a past year or answer BI questions.