You could simply add a computed column to your table:
ALTER TABLE dbo.YourTable
ADD regMonth AS MONTH(regDate) PERSISTED
and be done with it. This will be computed, persisted (e.g. not recomputed on every access, but only when regDate
changes), contains the MONTH information for the date, and can even be indexed for speed.
Update: ok, so now I get it - your "identity per month" is a bit unclear and misleading. What you want is to sequentially number the entries for each month, right?
One way to do it is not doing it / not storing it, but using burnall
's approach with the ROW_NUMBER() function.
Otherwise, you'd have to do an AFTER INSERT
trigger which calculates the new value upon INSERT
- but that gets a) messy and b) will cost you quite a bit of performance when you're doing lots of inserts.
My recommendation would be to use burnall
's function and let that run e.g. once every hour or so to update those fields. Do not try to figure this out on the fly, upon INSERT
- your performance will be awful.