【问题标题】:Auto increment considering Tenant id in existing table考虑现有表中的租户 ID 自动递增
【发布时间】:2018-07-10 14:18:00
【问题描述】:

我有两张表 Tenants 和 Inovices。 Invoices 有tenant_id 列,我需要在Invoices 表中按tentan_id 添加invoice_number 增量字段。

我的问题与Auto increment considering Tenant id相同

实际上,此解决方案对我有用,但现在我需要在此解决方案中应用触发器之前填写表中现有行的 invoice_number 增量字段。

类似这样,但按tenant_id递增:

DECLARE @invoice_number INT 
SET @@invoice_number = 0 
UPDATE Invoices
SET @invoice_number = invoice_number = @invoice_number + 1 
GO 

如何按每个租户循环和递增?

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    您可以使用以下解决方案

    • Tenants 表中添加invoice_seq 列,这样Tenants 表应该看起来像Tenants(tenant_id,name,...,invoice_seq),所以在创建发票时,请执行以下步骤
      1. 增加表InvoiceTenants中的invoice_seq
      2. 通过设置invoice_number ='I' format(tenant_id,'000') + '-' + format(invoice_seq,'000000')更新Invoice记录

    您的发票编号如下所示:

    I001-000001 <-- tenant 1 and sequence 1
    I001-000002
    I001-000003 <-- tenant 1 and sequence 3
    I002-000001 <-- tenant 2 and sequence 1
    I003-000001 <-- tenant 3 and sequence 1
    

    ** 示例代码 **

    -- 对于下面的例子,我将使用@tenant = 1,下面的代码可以转换为你的应用程序后面代码的存储过程

    declare @invoice_seq int,
            @tenant int = 1 -- here you can change the number to the way you wish
    
    -- retrieve the last tenant +1
    
    select @invoice_seq = invoice_seq+1 from Tenants where tenant_id=@tenant
    
    -- add the invoice
    
    insert into Invoices(tenant_id,invoice_number,... other columns....)
    values (@tenant,'I' + format(@tenant,'000') + '-' + format(@invoice_seq,'000000'),... other columns...)
    
    -- update the invoice_seq in the Tenants table
    
    update Tenants set invoice_seq = @invoice_seq where tenant_id=@tenant
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 2014-09-22
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 2023-03-27
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多