CREATE TRIGGER [dbo].[TR_dbo_GlLoan_LoanNumber] ON [dbo].[GlLoan] AFTER INSERT
AS
BEGIN
if @@ROWCOUNT = 0
return
SET NOCOUNT ON;
declare @count int;
set @count= (select max(loannumber) from glloan where branchid=(select branchid from inserted) and CompanyId=(select CompanyId from inserted))
update glloan set loannumber=@count+1 where id=(select id from inserted)
END
GO
是否有可能为某个分支机构和公司重复贷款编号?
答案 0 :(得分:0)
从我的评论中 - 如果我们可以安全地假设没有删除任何行,我会改为创建这个结构:
CREATE TABLE _GILoan (
/* Columns as currently, except no loannumber column */
_Id int IDENTITY(1,1) not null /* or is Id already defined so? */
)
GO
CREATE VIEW GILoan
AS
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY branchid,companyid
ORDER BY _Id) /* Or Id */
as LoanNumber
FROM _GILoan
GO
然后以与使用表格相同的方式处理此视图。 LoanNumber
是自动计算的(如我所说),如果没有删除任何行,则分配的数字不会改变。
答案 1 :(得分:0)
我们可以添加多列的唯一约束。
ALTER TABLE dbo.glloan
ADD CONSTRAINT ucLoanNumber UNIQUE (BranchId, CompanyId, LoanNumber)
在插入触发器之前使用计算贷款数量。因此,任何重复项都不会被插入。