【问题标题】:Stored procedure copying from one to another存储过程从一个复制到另一个
【发布时间】:2016-10-04 02:59:44
【问题描述】:

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

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

现在我有点迷失了:如何解决一旦删除并重新创建 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

我已经在我的问题中解释了我想要做什么

【问题讨论】:

  • 请分享您的代码以及您遇到的问题
  • 对于初学者,您需要一个已更改名称的列的列表。然后您可以按照此示例使用sp_renamestackoverflow.com/questions/16296622/…。您目前如何生成脚本来更改Sales 表?
  • 我已经添加了我的代码,请检查
  • 所以您是说您更改了Sales 表中的列名,现在您的SP 不起作用,因为该列不存在?这里没有复杂的答案——您只需要更改您的存储过程和/或您的SalesHistory 表即可。因此,无论您当前使用什么过程来捕获和迁移对Sales 的更改,还需要为您的存储过程和/或SalesHistory 表包含一个更改脚本。您没有提到您的 SalesHistory 表是否允许更改。如果没有,您想对添加的新列做什么?将值保留为 NULL?
  • 您能否澄清一下声明:“现在我有点迷失了:如何解决一旦删除并重新创建了 sales 表,我该如何修改 saleshistory 表的这些更改?”你的意思是数据变化,还是架构列变化

标签: sql-server


【解决方案1】:

假设您在删除表时正在跟踪数据...?

很遗憾,您不能为 DDL 语句(例如 drop table)创建代替触发器。因此,您不能在删除表之前简单地复制数据。但是,您可以在 Sales 表上创建一个 After Insert, Update 触发器,将记录直接插入到 SalesHistory。这样,当 Sales 表被随机删除时,SalesHistory 表中就已经有数据了。

注意:请小心使用触发器,因为它们可能会根据您的应用程序产生不需要的结果。此外,如果您无法控制 Sales 表的架构,那么您会发现很难将所有列的表数据复制到 SalesHistory 表并确保它在应用程序的整个生命周期内都有效。

但是,如果 Sales 表中有一个预定义的永远不会改变的列列表,那么您可以执行您所追求的,只需复制那些永远不会改变的列。

【讨论】:

  • 忘了提一件事,当我删除一个销售表时,我也将名称存储在销售映射表中。我们可以解决的问题也是如此
猜你喜欢
  • 2011-03-16
  • 2018-07-04
  • 2010-12-22
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多