1

您好我正在尝试将数据导入我的数据仓库并简化一些数据的导入,我想在表中创建一个新列,以便在获取新数据时跟踪最新值。

我的表如下所示:

CREATE TABLE CustomerFact(
 Id INT IDENTITY PRIMARY KEY
,CustomerId NVARCHAR(20) NOT NULL --Current Id of a Customer
);

--Track changes to CustomerId
CREATE TABLE CustomerHistoryFact(
 Id INT IDENTITY PRIMARY KEY
,CurrentCustomerId NVARCHAR(20) --Most recent Customer Id
,CustomerId NVARCHAR(20) NOT NULL --Customer Id at time of record insert
,PrvsCustomerId NVARCHAR(20) NOT NULL --Customer Id at time of transaction
,PrvsCustomerIdEffectiveDate DATE NOT NULL --Date when PrvsCustomerId was effective
,PrvsCustomerIdObsoleteDate DATE NOT NULL --When the PrvsCustomerId was expired and replaced with a new Customer Id
);

CustomerIdPrvsCustomerId和都是外部的PrvsCustomerIdEffectiveDatePrvsCustomerIdObsoleteDate我想在CurrentCustomerId插入新记录时分配一个。

这取决于何时插入新记录,CustomerHistoryFact检查所有其他记录。如果匹配,则新记录的 成为所有先前记录的 ,否则插入记录并成为。PrvsCustomerIdCurrentCustomerIdCustomerIdCurrentCustomerIdCustomerIdCurrentCustomerId

4

1 回答 1

0

似乎是一个扭曲的数据库设计。为什么每次更新记录CustomerId时都不能继续插入表?如果排序的最新 CustomerId与 Inserted/Deleted 表中的 customerId 不同,您可以在表上编写触发器以进行插入/更新,并在表中输入条目。这样,您就有了从当前 CustomerId 开始到及时返回的 CustomerId 的历史记录。CustomerHistoryFactCustomerFactCustomerFactCustomerHistoryFactCustomerIdEffectiveDate desc

CREATE TABLE CustomerFact(
 Id INT IDENTITY PRIMARY KEY
,CustomerId NVARCHAR(20) NOT NULL --Current Id of a Customer
);

--Track changes to CustomerId
CREATE TABLE CustomerHistoryFact(
 Id INT IDENTITY PRIMARY KEY
,CustomerId NVARCHAR(20) --Most recent Customer Id
,PrevCustomerId NVARCHAR(20) NOT NULL --Customer Id at time of record insert
,UpdatedDate DATETIME NOT NULL --Date when PrvsCustomerId was effective
);

CREATE TRIGGER dbo.CustomerFact_IU
ON dbo.CustomerFact
AFTER INSERT, UPDATE
AS 
BEGIN
    SET NOCOUNT ON;

    --
    -- Check if this is an INSERT, UPDATE.
    -- 
    DECLARE @action as char(1);
    DECLARE @oldCustomerId NVARCHAR(20);

    SET @action = 'I'; -- Set Action to Insert by default.
    IF EXISTS(SELECT * FROM DELETED)
    SELECT @oldCustomerId = customerId from DELETED
    BEGIN
        SET @action = 
            CASE
                WHEN EXISTS(SELECT * FROM INSERTED) THEN 'U' -- Set Action to Updated.
                ELSE 'D' -- Set Action to Deleted.       
            END
    END
    ELSE 
        IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.

    IF @action = 'I' OR @action = 'U'
    BEGIN
         INSERT INTO dbo.CustomerHistoryFact
         SELECT CustomerId, @oldCustomerId, GETUTCDATE() FROM INSERTED 
    END 

    END
于 2012-11-29T16:26:23.153 回答