Code _mssql to generate a duplicate order number using SQL functions

Source: Internet
Author: User
Copy Code code as follows:

ALTER function [dbo]. [Getordernum] (
@ebaystockflag varchar (20)//rule Letter
)
Returns varchar (100)
As
BEGIN
DECLARE @dt CHAR (8)
DECLARE @flag varchar (20)
Set @flag = ' B ' + @ebaystockflag
Set @dt =convert (CHAR (8), GETDATE (), 112)
DECLARE @max varchar (100)
SELECT @max =max (ordernumber)
From Tb_ebayorder with (Xlock,paglock)
WHERE ordernumber like @flag + '% '
Set @max =isnull (@max, @flag + @dt + ' 000 ')--cannot find the result and give a default value
DECLARE @a varchar (100)
DECLARE @num varchar (10)
DECLARE @ordernum varchar (20)
Set @a=convert (Varchar,right (@max, Len (@max)-10)--intercept the digital portion
if (left (@a,1) =0)--starts with 0
Begin
if (SUBSTRING (@a,2,1) =0)--there are two 0
Begin
Set @num =convert (varchar,substring (@a,3,len (@a-2)) +1)

End
else if (SUBSTRING (@a,3,1) =0 and SUBSTRING (@a,2,1) =0)--three 0
Begin
Set @num =1

End
Else begin--only one 0 of the case
Set @num =convert (int,substring (@a,2,len (@a)) +1)

End
End
Else begin-The case where the number is greater than 100
Set @num =convert (varchar,@a+1)
End

if (LEN (@num) =1)--0 less than three digits after interception
Begin Set @num = ' + ' + @num end
if (LEN (@num) =2)
Begin set @num = ' 0 ' + @num end
Set @ordernum = @flag + @dt + @num
Return @ordernum
End

Call: Locks the table to be manipulated first in a transaction
Copy Code code as follows:

SELECT * from Tb_ebayorder with (Tablockx)
SELECT * from Tb_ebayorderlist with (Tablockx)
SELECT * from Tb_ebayorderuserinfo with (Tablockx)

Call: SELECT dbo. Getordernum (@ebaystockflag)

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.