復制代碼 代碼如下:
ALTER function [dbo].[GetOrderNum](
@ebaystockflag varchar(20)//規則字母
)
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')--查不到結果給個默認值
declare @a varchar(100)
declare @num varchar(10)
declare @ordernum varchar(20)
set @a=Convert(varchar,right(@max,len(@max)-10))--截取數字部分
if(LEFT(@a,1)=0)--以0開頭
begin
if(SUBSTRING(@a,2,1)=0)--有兩個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)--有三個0
begin
set @num=1
end
else begin --只有一個0的情況
set @num=Convert(int,SUBSTRING(@a,2,LEN(@a))+1)
end
end
else begin --數字大於100的情況
set @num=Convert(varchar,@a+1)
end
if(LEN(@num)=1)--截取後不滿三位的補0
begin set @num='00'+@num end
if(LEN(@num)=2)
begin set @num='0'+@num end
set @ordernum=@flag+@dt+@num
return @ordernum
END
調用:在事務中先鎖定要操作的表
復制代碼 代碼如下:
SELECT * FROM tb_EbayOrder WITH (TABLOCKX)
SELECT * FROM tb_EbayOrderList WITH (TABLOCKX)
SELECT * FROM tb_EbayOrderUserInfo WITH (TABLOCKX)
調用:select dbo.GetOrderNum(@ebaystockflag)