Solution to automatic growth of business order number

Source: Internet
Author: User

Problem: in actual business processing, some ticket numbers need to grow automatically, but they cannot be replaced by auto-increment columns.
Eg: p031106001 -- the first p represents the purchase order, 031106 represents the date, and the last three are the sequential number.

/* 1: Create a table structure for testing */
Create Table tablename (Pono char (10), B INT)
Go
/* 2: Create a view to get the current date and prepare for the UDF below */
Create view vgetdate
As
Select getdate () as today
Go
/* 3: Use a custom function to obtain the ticket number (because getdate () cannot be used in the custom function to obtain the current date, the preceding view is required )*/
Create Function getdh ()
Returns char (10)
As
Begin
Declare @ dh1 char (10), @ DH2 char (10)
Select @ dh1 = max (Pono) from tablename
Set @ dh1 = isnull (@ dh1, 'p000000000 ')
Select @ DH2 = left (@ dh1, 1) + right (convert (varchar (8), today, 112), 6) + '001' from vgetdate
If @ dh1 >=@ DH2
Begin
Set @ DH2 = left (@ dh1, 7) + right ('000' + Cast (cast (right (@ dh1, 3) as INT) + 1 as varchar), 3)
End
Return (@ DH2)
End
Go
/* 4: Enter DBO. getdh () */in the default field ()*/
Alter table tablename add constraint df_tablename_1 default (DBO. getdh () for Pono
-/* 5: Test :*/
Insert tablename (B) values (1)
Insert tablename (B) values (2)
Select * From tablename
-- Test Result
Pono B
---------------------
P031115001 1
P031115002 2
Conclusion: Some tips have been applied to this method.
1: use the default field value to realize auto-increment of ticket numbers
2: Use a UDF to obtain the default value of a field.
3: Because undefined functions such as getdate () cannot be used in user-defined functions, views are used to get the current date.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.