如果仅动态需要参考编号,则可以根据您的确切标准创建一个视图:
CREATE VIEW Acc.PartitionedDocument
AS
SELECT DocumentID,
Date,
SalesCompanyFinancialPeriod,
DocumentTypeID,
ROW_NUMBER() OVER(PARTITION BY SalesCompanyFinancialPeriod ORDER BY DocumentID) [PartitionDocumentID]
FROM Acc.Document
但是,如果删除文档,这将改变。否则,据我所知,使用 SQL-Server 2008 的唯一选择是使用触发器或在应用程序层内维护序列。下面是我如何使用触发器来实现这一点。
-- ADD ADDITIONAL COLUMN
ALTER TABLE Acc.Document ADD ParitionDocumentID INT NULL
GO
-- UPDATE EXISTING ROWS
;WITH Doc AS
( SELECT *, ROW_NUMBER() OVER(PARTITION BY SalesCompanyFinancialPeriod ORDER BY DocumentID) [RowNumber]
FROM Acc.Document
)
UPDATE Doc
SET PartitionDocumentID = RowNumber
GO
-- ADD CONSTRAINT TO ENSURE NO DUPLICATES
ALTER TABLE Acc.Document ADD CONSTRAINT UQ_Acc_Document UNIQUE NONCLUSTERED (PartitionDocumentID, SalesCompanyFinancialPeriodID)
GO
-- ADD TRIGGER TO MAINTAIN NEW COLUMN
CREATE TRIGGER acc.InsertDocument
ON Acc.Document
FOR INSERT
AS
IF EXISTS(SELECT 1 FROM inserted WHERE PartitionDocumentID IS NULL)
BEGIN
UPDATE Acc.Document
SET PartitionDocumentID = COALESCE(NextDocumentID, 0) + RowNumber
FROM Acc.Document d
INNER JOIN
( SELECT DocumentID, ROW_NUMBER() OVER(PARTITION BY SalesCompanyFinancialPeriodID ORDER BY DocumentID) [RowNumber]
FROM inserted
WHERE PartitionDocumentID IS NULL
) i
ON i.DocumentID = d.DocumentID
LEFT JOIN
( SELECT SalesCompanyFinancialPeriodID, MAX(PartitionDocumentID) [NextDocumentID]
FROM Acc.Document
GROUP BY SalesCompanyFinancialPeriodID
) NextID
ON NextID.SalesCompanyFinancialPeriodID = d.SalesCompanyFinancialPeriodID
END