views:

420

answers:

3

I have a requirement for a program I'm working on to store job numbers as YY-###### with incrementing numbers starting at 000001 in each year preceded by the last two digits of the year.

The only method I've been able to come up with is to make a CurrentJob table and use an identity column along with the last two digits of the year and an ArchiveJob table and then combining the two via a union in a view. Then I'd have to copy the CurrentJob to ArchiveJob at the begining of the year and truncate CurrentJob.

Is there an easier way to restart the numbering (obviously not having it be an Identity column) in one table?

The client is closed on New Years so there should be no data entry at the change of the year (for a school).

+3  A: 

An identity column is by far the fastest and most concurrent solution to generating sequential numbers inside SQL Server. There's no need to make it too complicated though. Just have one table for generating the identity values, and reset it at the end of the year. Here's a quick example:

-- Sequence generating table
create table SequenceGenerator (
    ID integer identity(1, 1) primary key clustered
)

-- Generate a new number
insert into SequenceGenerator default values
select @@identity

-- Reset the sequence
truncate table SequenceGenerator
if ident_current('SequenceGenerator') <> 1 begin
    dbcc checkident('SequenceGenerator', reseed, 0)
    dbcc checkident('SequenceGenerator', reseed)
end else begin
    dbcc checkident('SequenceGenerator', reseed, 1)
end
Christian Hayter
+1  A: 

There is a similar question #761378.. (Note: it uses MySql but the principle is the same)

The accepted answer suggested using a second table to manage the current ID.

However the most popular question was to not do this! Please note HLGEM's answer on the post for reasons why not to.

Nathan Koop
HLGEM's answer on that post makes perfect sense if you are talking about a unique row identifier designed by the developer. If you are talking about an external identifier specified in the business requirements, then HLGEM's answer is not relevant. This particular question has not yet specified what the requirements are, so let's reserve judgement.
Christian Hayter
@Christian, I understand your point, but when I hear that he's using an Identity column I presume (and I believe it's a safe assumption) that it's the Primary Key.
Nathan Koop
A: 

You can use the "reseed" command from here to reset the starting value.

David