1

我的表结构如下:

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 无关。

4

1 回答 1

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
于 2012-06-07T08:05:41.533 回答