sql server 按照日期自動生成單據編號的函數
一、sql server 按照日期自動生成單據編號的函數,格式為##08080001,##表示打頭的單據字符,然后是年月和流水編號。三、一般的調用格式為dbo.GetCostBillID('HP',getdate())
--按單號和年月獲取單據的編號
CREATE FUNCTION GetCostBillID(@headStr nvarchar(10),@date datetime)
RETURNS nvarchar(50)
BEGIN
declare @oid2 nvarchar(50)
declare @oid nvarchar(50)
declare @month nvarchar(2)
declare @year nvarchar(2)
declare @ym nvarchar(4)
set @month=month(@date)
if len(@month)=1
set @month='0'+@month --使月為兩位長
set @year=right(convert(nvarchar,year(@date)),2)
set @ym=@year+@month --組成年月字符
--格式CB0808001
if exists(select * from CostBill)
begin
select top 1 @oid2=CostBillID from CostBill order by id desc --獲取最后一條的單據編號,一定要有id,並且自動生成的,倒排序
end
else
begin
set @oid2=@headStr+@ym+'0000' --沒有記錄是默認為今天
end
--訂單不是本月的,重新開始一個新的訂單流水號
if convert(nvarchar,left(@oid2,6))<>@headStr+@ym
begin
--用本月的年月號開始
set @oid2=@headStr+@ym+'0000'
end
declare @str nvarchar(50) --臨時單號
set @str=convert(nvarchar,(convert(int,right(@oid2,4))+1)) --訂單號加一
while (4-len(@str)>0)
begin
set @str='0'+@str
end
set @oid2=@headStr+@ym+@str
--print @oid2
--如果該訂單好已經存在,則重新獲取
while exists(select * from CostBill where CostBillID=@oid2)
begin
set @str=convert(nvarchar,(convert(int,right(@oid2,4))+1)) --訂單號加一
while (4-len(@str)>0)
begin
set @str='0'+@str
end
set @oid2=@headStr+@ym+@str
-- print @oid2
end
set @oid=convert(nvarchar,@oid2)
--print 'HP'+convert(nvarchar,year(getdate()))+convert(nvarchar,month(getdate()))+@str
RETURN @oid
END