我的表结构如下:
CREATE TABLE [ACC].[Document](
[DocumentID] [int] IDENTITY(1,1) NOT NULL,
[Date] [date] NOT NULL,
[SalesCompanyFinancialPeriodID] [int] NOT NULL,
[DocumentTypeID] [int] NULL,
CONSTRAINT [PK_Document] PRIMARY KEY CLUSTERED
(
[DocumentID] ASC
)
我想在SalesCompanyFinancialPeriodID
列上对我的表进行分区。是否可以在每个分区上重置DocumentID列值。换句话说,每个分区中的DocumentID独立于其他分区中的DocumentID。
答案 0 :(得分:1)
根据您的确切标准,如果只需动态参考号码,您就可以创建视图:
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