2017-10-28 140 views
0

我的客户希望根据他们工作的财政年度(4月当年到明年3月)为每个票据编号生成一个代码,并且财务年度更改时需要重置为0的数字如何使用财政年度的前缀生成自动增量编号?

例如:

ID 
17/18/0000001 
17/18/0000002 
... 
18/19/0000001 
18/19/0000002 
... 

enter image description here

如果财政年度存储在数据库就像一个结束的月份和年份开始。我们如何检查这是下一年的布罗达!重置数字。

回答

0

我不会尝试在内部维护这样的计数器。相反,我会在查询时产生。下面的查询假设您的表有一个财政年度的int列,它只有一个普通自动增量计数器ID以及一个year int列。我们可以使用下面的生成你想要的计数器:

SELECT 
    RIGHT(CONVERT(varchar(4), year), 2) + '/' + 
    RIGHT(CONVERT(varchar(4), year + 1), 2) + '/' + 
    RIGHT('0000000' + 
     CAST(ROW_NUMBER() OVER (PARTITION BY year ORDER BY ID) AS VARCHAR), 7) 
FROM yourTable; 

Demo

+0

我不得不使用它,因为我需要根据会计年度生成门票号码。随着年份周期的变化,门票号码需要重置 –

+0

@InfiRazor也许别人会给你你想要的答案。自动增量列_必须是唯一的。因此,我认为,SQL Server内部的任何方案都会相当复杂。 –

0

客户永远是对的。假设你有一个表

create table #trans(
    id int identity(1,1), 
    transDate datetime 
    --other fields 
    ) 
--the table is filled 

declare @dStart date='20160401', --start and end dates 
     @dEnd date='20170331' --of the first financial year 

;with fy as (-- fill following years 
select 1 id, @dStart dStart, @dEnd dEnd 
union all 
select id+1,DATEADD(year,1,dStart),DATEADD(year,1,dEnd) 
from fy 
where id<5 --"majic" 5 is arbitrary 
) 
select dStart,dEnd,t.*, 
    right(cast(year(dstart) as varchar),2)+'/'+right(cast(year(dEnd) as varchar),2)+'/' -- F.Y. label 
    + FORMAT(ROW_NUMBER() over(
     partition by right(cast(year(dstart) as varchar),2)+'/'+right(cast(year(dEnd) as varchar),2)+'/' --restart numbering each F.Y. 
     order by t.id),'000000') ticket 
from fy 
inner join #trans t on cast(t.transDate as date) between fy.dStart and fy.dEnd 

并且有客户想要什么。
免责声明:如果删除了一些数据,则票号更改。

相关问题