tsql - Where/How to Create Reference Number -


i'm using entity framework , mssql...

i need insert custom reference number when record inserted. format yyyy-01, yyyy-02, etc sequential number needs reset when new year begins.

for example 2011-01, 2011-02, 2012-01

i'm curious if should go trigger or manage ef or ?

having sequential numbering reset each year has me little confused...

thanks advice!

update:
sorry, couldn't code tag work 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 trigger. create 2 column table stores year , current record number , uses trigger current year, increment count column one, return count trigger. build logic trigger if new year doesn't exist, insert new year record. know people avoid triggers if possible that's pretty legit use of trigger , way less processing trying count records on every insert.

having single row every year , it's related count may prove useful in future when you're trying audit past year or answer bi questions.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -