存储过程从一个复制到另一个。

29 浏览
0 Comments

存储过程从一个复制到另一个。

我有一个名为Sales的表和另一个名为SalesHistory的表。 SalesHistorySales表的副本。

现在Sales表可以随时被删除并重新创建,新列被添加并将旧列重命名为不同的名称。我编写了一个存储过程,根据插入或更新的条件,将数据从sales表复制到saleshistory表中。

现在我有点迷失:一旦销售表被删除并重新创建,我该如何将这些更改修正到销售历史表中?

有什么想法或相同的代码,如果需要,我可以分享我的存储过程代码,但那很简单。

这是代码

Insert into SalesHistory (Cusip, KeyFeatures1, KeyFeatures2, KeyFeatures3, KeyFeatures4, KeyFeatures5, KeyFeatures6, KeyFeatures7, KeyRisks1, KeyRisks2, KeyRisks3, Comments1, Comments2, Comments3)
    select 
        Cusip, KeyFeatures1, KeyFeatures2, KeyFeatures3, KeyFeatures4, 
        KeyFeatures5, KeyFeatures6, KeyFeatures7, KeyRisks1, KeyRisks2, 
        KeyRisks3, Comments1, Comments2, Comments3 
    from 
        Sales 
    where 
        not exists (SELECT 1 FROM SalesHistory WHERE cusip  = Sales.cusip)
UPDATE Hist 
SET Cusip  = A.Cusip,
    KeyFeatures1 = A.KeyFeatures1,
    KeyFeatures2 = A.KeyFeatures2,
    KeyFeatures3 = A.KeyFeatures3,
    KeyFeatures4 = A.KeyFeatures4,
    KeyFeatures5 = A.KeyFeatures5,
    KeyFeatures6 = A.KeyFeatures6,
    KeyFeatures7 = A.KeyFeatures7,
    KeyRisks1 = A.KeyRisks1,
    KeyRisks2 = A.KeyRisks2,
    KeyRisks3 = A.KeyRisks3,
    Comments1 = A.Comments1,
    Comments2 = A.Comments2,
    Comments3  = A.Comments3
FROM  
    SalesHistory Hist 
INNER JOIN 
    Sales A ON A.cusip  = Hist.cusip

我已经在我的问题中解释了我正在尝试做什么。

admin 更改状态以发布 2023年5月23日
0
0 Comments

假设您想在删除表时获取数据...?

不幸的是,您无法为DDL语句(如删除表)创建代替触发器。因此,您无法在删除表之前简单地复制数据。但是,您可以在Sales表上创建一个After Insert、Update触发器,该触发器立即将记录插入SalesHistory。这样,当Sales表被随机删除时,您将已经拥有SalesHistory表中的数据。

注:请注意触发器,因为它们可能会根据您的应用程序产生不希望的结果。此外,如果您无法控制Sales表的模式,则很难将表数据复制到SalesHistory表中的所有列并确保其在应用程序的整个生命周期内正常工作。

但是,如果Sales表中有一个预定义的列列表永远不会更改,那么您可以执行您想要的操作,并仅仅复制那些永不更改的列。

0