【问题标题】:How to generate AutoIncrement number with prefix of financial year?如何生成带有财政年度前缀的自动增量编号?
【发布时间】:2018-04-09 22:14:16
【问题描述】:

我的客户希望根据他们工作的财政年度(当年 4 月至明年 3 月)为进入数据库的每个票号生成一个代码,并且在财政年度发生变化时,号码需要重置为 0

例子:

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

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

【问题讨论】:

    标签: sql-server datetime auto-increment


    【解决方案1】:

    客户永远是对的。假设你有一张桌子

    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
    

    并拥有客户想要的东西。
    免责声明:如果删除了某些数据,则票证编号会更改。

    【讨论】:

      【解决方案2】:

      我不会尝试在内部维护这样的计数器。相反,我会在查询时生成。下面的查询假定您的表确实有一个普通的自动增量计数器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

      【讨论】:

      • 我不得不使用它,因为我需要根据财政年度生成票号。随着年份周期的变化,票号需要重新设置
      • @InfiRazor 也许别人会给你你想要的答案。自动递增列必须是唯一的。因此,我认为 SQL Server 内部的任何方案都会相当复杂。
      猜你喜欢
      • 2023-03-18
      • 2015-10-22
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多