4

在我的项目中,我不得不用更多的列来扩展现有的表。不幸的是,我无法更改或删除/重新创建它,所以我只是选择创建另一个具有 1:1-Relationship 的表,并使用 Insert/Update/Delete-Triggers 将它们合并到一个视图中。

到目前为止,插入和删除都有效,但我对更新触发器有疑问。成功消息更加令人困惑。

视图如下所示:

Create View [dbo].[JoinedGroups] as
SELECT [dbo].[MaterialGroups].[GroupID]
      ,[Name]
      ,[SupGroup_ID]
      ,[ExtGroup_ID]
  FROM [dbo].[MaterialGroups]
 left outer join [dbo].[MaterialGroups_Extend]
 ON [dbo].[MaterialGroups].[GroupID]=[dbo].[MaterialGroups_Extend].[GroupID]

如前所述,新的附加表尚未填充,这就是左外连接的原因,但如果您有不同的想法,请告诉我。

触发:

CREATE TRIGGER [dbo].[UpdateTriggerJG] ON [dbo].[JoinedGroups]
INSTEAD OF Update
AS
BEGIN
IF EXISTS (SELECT * FROM [dbo].[MaterialGroups_Extend] E,inserted I WHERE E.[GroupID] = I.[GroupID])
BEGIN
   UPDATE [dbo].[MaterialGroups_Extend]
   SET [SupGroup_ID] = I.[SupGroup_ID]
      ,[ExtGroup_ID] = I.[ExtGroup_ID]
      FROM [Buran].[dbo].[MaterialGroups_Extend] E,inserted I
   WHERE E.[GroupID] = I.[GroupID]
END
   ELSE
   BEGIN
   INSERT INTO [dbo].[MaterialGroups_Extend]
           ([GroupID]
           ,[SupGroup_ID]
           ,[ExtGroup_ID])     
      SELECT [GroupID]
           ,[SupGroup_ID]
           ,[ExtGroup_ID]
      FROM inserted
      END
   UPDATE [dbo].[MaterialGroups]
   SET [dbo].[MaterialGroups].[Name] = I.Name
   FROM [dbo].[MaterialGroups],inserted I
   WHERE [dbo].[MaterialGroups].[GroupID] = I.[GroupID]

像这样的声明:

UPDATE [dbo].[JoinedGroups]
   SET 
      [SupGroup_ID] = 1
      ,[ExtGroup_ID] = 1

给出以下输出:

(2 row(s) affected)

(23 row(s) affected)

(23 row(s) affected)

这有点有趣:[MaterialGroups] 包含 23 行数据 [MaterialGroups_Extend] 包含 2 行数据视图也有 23 行。

但是为什么没有插入任何东西?我做错了什么还是忘记了什么?

4

1 回答 1

5

尝试重写您的触发器,例如:

CREATE TRIGGER [dbo].[UpdateTriggerJG] ON [dbo].[JoinedGroups]
INSTEAD OF Update
AS
begin
    update dbo.MaterialGroups_Extend set
        SupGroup_ID = I.SupGroup_ID,
        ExtGroup_ID = I.ExtGroup_ID
    from dbo.MaterialGroups_Extend as E
        inner join inserted I on I.GroupID = E.GroupID

    insert into dbo.MaterialGroups_Extend
    (
        GroupID,
        SupGroup_ID,
        ExtGroup_ID
    )     
    select
        GroupID,
        SupGroup_ID,
        ExtGroup_ID,
    from inserted as i
    where
        not exists
        (
             select *
             from dbo.MaterialGroups_Extend as E
             where E.GroupID = I.GroupID
        )

    update dbo.MaterialGroups set
        Name = I.Name
    from dbo.MaterialGroups as MG
        inner join inserted I on I.GroupID = MG.GroupID
end
于 2013-09-04T19:21:41.887 回答