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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值