You could have a general issue id and a category, for example:
Table: Issue
------------------------------------
IssueID | CategoryID | CategoryIndex
------------------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 1 | 3
Table: Category
-----------------------------
CategoryID | Prefix | Name
-----------------------------
1 | INF | IT
2 | GEN | General
Then you calculate the issue number when querying these tables.
You can store the calculated number in a table if you want to keep track of the issue number in case of a change in the database (ex: the prefix for IT related questions changes from INF
to IT
)
Now that you have a good schema, how do you keep control of the category sequence on the issues table? Check this out:
DECLARE @categoryID INT
DECLARE @nextSequence INT
SET @categoryID = 1 --You'll have to change this!
SELECT @nextSequence = i.CategoryIndex
FROM Issue i
WHERE i.CategoryID = @categoryID
SELECT COALESCE(@nextSequence, 0) + 1 as 'NextSequence'
You can turn that into a stored procedure (NextSequence
, maybe?) that receives an INT
as parameter (the category ID) and returns another INT
as result (the CategoryIndex
for the new issue).
Finally, to create your full code:
SELECT
i.IssueID
, c.Prefix + '-' + RIGHT('0000' + CONVERT(VARCHAR(4), i.CategoryIndex), 4) as 'IssueCode'
FROM Issue i
INNER JOIN Category c ON i.CategoryID = c.CategoryID