复制代码 代码如下:
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)