0

我有一个具有 InvoiceID (int identity) 主键的发票表。和一列 InvoiceNumber,它是一个整数。我有另一个表用于生成名为 Invoice_Numbers 的发票编号(见下文)。为了确保发票号码是唯一的并防止出现空白,我实施了以下代码。有人可以查看此代码并评论其可靠性。在多用户环境中运行 SQL 2008。

用户在插入发票时致电然后进行采购时获得相同发票编号的机会有多大?

 
如果存在
   (选择 *
    FROM 系统对象
    WHERE object_id = OBJECT_ID(N'[Imports].[Invoices_Numbers]')
           并输入(N'U'))
  DROP TABLE [Imports].[Invoices_Numbers]

CREATE TABLE [进口].[Invoices_Numbers] ( [InvoiceNumber] [INT] IDENTITY(1, 1) 非空 ,[已删除] [BIT] 非空 ,[已使用] [BIT] 不为空, 约束 [PK_Invoices_Numbers] 主键集群([InvoiceNumber] ASC)与(PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON)ON [PRIMARY] ) 开 [主要]

ALTER PROCEDURE [进口].[Get_Invoice_Number] ( @InvoiceNumber INT 输出 ) 作为 开始 声明 @NewNumber INT 声明 @MinNumber INT

BEGIN TRAN SELECT @MinNumber = MIN(InvoiceNumber) FROM Imports.Invoices_Numbers IF @MinNumber > 1 BEGIN SET IDENTITY_INSERT Imports.Invoices_Numbers ON; INSERT Imports.Invoices_Numbers ( Invoicenumber ,Deleted ,Used ) VALUES ( 1 ,0 ,1 ) SET IDENTITY_INSERT Imports.Invoices_Numbers OFF; SET @NewNumber=1 END ELSE BEGIN WITH Gaps AS (SELECT TOP 1 a.InvoiceNumber + 1 AS GapValue FROM Imports.Invoices_Numbers a WHERE NOT EXISTS (SELECT * FROM Imports.Invoices_Numbers b WHERE b.InvoiceNumber = a.InvoiceNumber + 1) AND a.InvoiceNumber < (SELECT MAX(InvoiceNumber) FROM Imports.Invoices_Numbers)) SELECT @NewNumber = GapValue FROM Gaps IF @NewNumber IS NULL BEGIN SELECT TOP 1 @NewNumber = InvoiceNumber FROM Imports.Invoices_Numbers WHERE Used = 0 AND Deleted = 0 ORDER BY InvoiceNumber IF @NewNumber IS NULL BEGIN INSERT Imports.Invoices_Numbers ( Deleted ,Used ) VALUES ( 0 ,1 ) SELECT @NewNumber = SCOPE_IDENTITY () END ELSE BEGIN UPDATE Imports.Invoices_Numbers SET Used = 1 WHERE InvoiceNumber = @NewNumber END END ELSE BEGIN SET IDENTITY_INSERT Imports.Invoices_Numbers ON; INSERT Imports.Invoices_Numbers ( Invoicenumber ,Deleted ,Used ) VALUES ( @NewNumber ,0 ,1 ) SET IDENTITY_INSERT Imports.Invoices_Numbers OFF; END END SELECT @InvoiceNumber = @NewNumber COMMIT TRAN

结尾

4

1 回答 1

1

您的解决方案看起来有点复杂。set identity_insert除了数据导入任务之外,我不建议使用它。

为了确保唯一性,我首先添加一个唯一约束:

alter table Invoices add constraint UX_Invoices_InvoiceNr unique

然后您可以使用这样的 SQL 语句插入发票:

while 1=1
    begin        
    declare @new_nr int
    select  @new_nr = max(InvoiceNr) + 1
    from    dbo.Invoices

    if @new_nr is null
        set @new_nr = 1

    insert  dbo.Invoices
            (InvoiceNr, ...)
    values  (@new_nr, ...)

    if @@rowcount = 1
        break
    end
于 2012-06-07T12:27:50.820 回答