【问题标题】:How to update another table if they are related?如果它们相关,如何更新另一个表?
【发布时间】:2016-01-27 11:33:03
【问题描述】:

我有两个表 tbLicence 和 tbCompanyAgent,如屏幕截图所示

在 tbCompanyAgent 中存在一些与 tbLicence 中相同的常见列值,例如 LicenseNumber、LicenseIssueDate 和 LicenseExpirationDate。在一些复杂的 sql 查询和业务需求之后,将 tbLicence 中的 StateIssuedLicenseNumber、StateIssuedLicenseIssueDate 和 StatedIssuedLicenseExpirationDate 列以及 LicenceNumber、DateIssued 和 ExpirationDate 列合并到 tbCompanyAgent 中的单个列 LicenseNumber、LicenseIssueDate 和 LicenseExpirationDate。

StateIssuedLicenseNumber、StateIssuedLicenseIssueDate 和 StatedIssuedLicenseExpirationDate 中的值对于由 Group Id Column LicenceType 标识的同一组记录也是相同的。

实际上,所有许可证都有一个常驻条目,存储在 StateIssuedLicenseNumber、StateIssuedLicenseIssueDate 和 StatedIssuedLicenseExpirationDate 列,由值为 1 的 Resident 列标识。

非居民许可证存储在 LicenceNumber、DateIssued 和 ExpirationDate 中,值为 0。

我的问题是,如果用户尝试在 tbLicence 中进行一些更新,这些更新应该反映在 tbCompanyAgent 上。我将如何编写查询。请帮忙!!!

【问题讨论】:

  • 你可以使用更新加入。
  • 能否提供查询...

标签: sql sql-server sql-server-2008


【解决方案1】:

您可以为此使用触发器。

https://msdn.microsoft.com/en-us/library/ms189799.aspx

它应该是 ON UPDATE 触发器。更新的行将在伪表中插入

这里你可以看到一个很好的例子

SQL Triggers - how do I get the updated value?

【讨论】:

  • 我无法使用触发器,因为我必须在循环中插入许可证并且要更新它们,我必须首先根据组 ID 列 LicenceType 一起删除所有许可证,然后重新插入它们在循环中。由于复杂的业务需求,我必须这样做。请提供替代查询...
  • 然后,我会说,您需要 AFTER INSERT 触发器。当它运行时,您需要从另一列中找到合适的行(通过在某些唯一属性上将表“插入”连接到 tbCompanyAgent)。如果你找到行 - 只需用新值更新它)。
猜你喜欢
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 2020-07-29
  • 2014-12-02
相关资源
最近更新 更多