防止发票号码重复针对特定 ID
我对如何防止针对 CompanyId
重复 InvoiceNo
感到困惑。我刚刚准备了一个发票项目,其中包含 CompanyId
和 InvNo
等字段。两者都没有唯一键,因为 Company ID 和 InvoiceNo 都必须重复。如下所示
CompanyID InvNo
1 1
2 1
1 2
3 1
4 1
1 3
现在我想针对特定 CompanyId 对重复的 InvoiceNo 触发 raiserror。我该如何实现这个。重要提示:如果我创建唯一索引,则不允许重复记录,并且重要的是允许除特定 CompanyId 之外的记录
I have confusion on how to prevent duplicate InvoiceNo
against CompanyId
. I just have prepare an Invoice project that has field like CompanyId
and InvNo
. Both do not have Unique Keys because Company ID and InvoiceNo both have to repeated. as per below
CompanyID InvNo
1 1
2 1
1 2
3 1
4 1
1 3
Now I want to fire a raiserror on duplicate InvoiceNo against a particular CompanyId. How do I implement this. Important: if i create a unique index then duplicate records will not be allowed and it is important to allow except against particular CompanyId
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找的是由 CompanyId 和 InvNo 组成的唯一约束。这将让您只为 CompanyId = 1 创建一张 InvoiceNo = 1,并且如果您尝试插入重复项,将自动引发 RaisError。它还可以让您为 CompanyId = 2 插入 InvoiceNo = 1 从而(希望)满足您的要求
这就是我在 SQL Server 中执行此操作的方式
What you are looking for is a Unique Constraint composed of both CompanyId and InvNo. This will let you create only one InvoiceNo = 1 for CompanyId = 1 and will automatically RaisError if you try to insert a duplicate. It will also let you insert InvoiceNo = 1 for CompanyId = 2 thereby (hopefully) satisfying your requiements
This is how I would do it in SQL Server
你的问题并不是那么直接,但假设你问的是我认为你在问的问题,它是这样的......
你需要一条名为 NextInvoiceNumber 的电缆,由 CompanyID 和 NextInvoiceNo 组成。创建一个新公司应该创建一个新的 NextInvoiceNumber - 因此也许可以在您的 Companies 表上使用插入触发器...
编写一个函数来获取特定公司的下一个发票 ID,然后递增 NextInvoiceNumber 表中的值(所有在公共事务中)。
因此,在伪代码中,类似
This function 的内容理想地属于数据库服务器上的 UDF。
Your question is not all that straight forward, but assuming you're asking what I think you're asking, it goes something like this...
You need a cable called NextInvoiceNumber, comprising of CompanyID and NextInvoiceNo. Creating a new Company should create a new NextInvoiceNumber - so perhaps use an insert trigger on your Companies table for that...
Write a function to get the next Invoice id for a specific company, and then incremenent the value in the NextInvoiceNumber table (all inside a common transaction).
So, in pseudo code, something like
This function ideally belongs on your database server as a UDF.
从示例数据来看,CompanyID + InvNo 的组合是唯一的。如果确实如此,您可以在这两个字段上创建一个键,并且在尝试插入已用于特定 CompanyID 的重复 InvNo 时,将引发错误。
From the sample data it appears that the combination of CompanyID + InvNo is unique. If that's true you can create a key on those two fields and upon an attempt to insert a duplicate InvNo that has already been used for a particular CompanyID an error would be thrown.