foreach行插入另一个表并更新列

时间:2015-02-11 16:32:49

标签: sql sql-update sql-insert

情况:Table1 CONSTRAINT FOREIGN KEYTable2名为Table2Id

如何更新Table2Id中每一行的Table1列,其中Table2新插入的行(每个Table1行都有自己的Table2记录) ?

1 个答案:

答案 0 :(得分:0)

我使用了以下代码在MS SQL-Server上执行此操作。我没有方便的代码,但在MySQL中实现了类似的触发器。

ALTER TRIGGER [dbo].[Addresses_afterInsert] 
   ON  [dbo].[Addresses] 
   AFTER INSERT
AS 
BEGIN
  INSERT INTO [MultiKey] ([keyEntity], [nameEntity], [typeEntity])
  SELECT [keyAddress], [fullAddress], 'Address' AS [typeEntity]
  FROM [Addresses]
  WHERE ([keyMulti] IS NULL);
  UPDATE [Addresses]
  SET [keyMulti] = [MultiKey].[keyMulti]
  FROM [Addresses]
  INNER JOIN [MultiKey]
    ON (
      ([MultiKey].[keyEntity] = [Addresses].[keyAddress])
      AND ([MultiKey].[typeEntity] = 'Address')
    );
END