在我的项目中,我不得不扩展一个包含更多列的现有表。不幸的是,我无法改变或删除/重新创建它,所以我选择创建另一个具有1:1-Relationship的表,并将它们合并到一个包含插入/更新/删除触发器的视图中。
到目前为止,insert和Delete有效,但我遇到了Update-Trigger的问题。成功的信息更令人困惑。
View看起来像这样:
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个。
但是为什么没有插入任何内容?我做错了什么或忘记了什么?
答案 0 :(得分: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