我有一个可更新的视图,它使用一个代替触发器来进行插入/更新。该触发器使用合并。我发现 Merge 语句没有应用来自底层物理表的默认约束,尽管合并文档建议它应该这样做。
以下示例演示:
create table tblTest
(
id uniqueidentifier not null primary key default newid(),
forename varchar(20),
surname varchar(20) not null default 'xxyyzz'
)
go
create view vwTest as select * from tblTest
go
create Trigger vwTest_trigger_insteadof_insert_update On vwTest
Instead of Insert, Update As
begin
set nocount on
Merge tblTest t
Using
inserted i On (t.id = i.id)
When Matched Then
Update
Set
t.forename = i.forename,
t.surname = i.surname
When Not Matched By Target Then
Insert
(
id,
forename,
surname
)
Values
(
i.id,
i.forename,
i.surname
)
OUTPUT $action, Inserted.*, Deleted.*
;
end
go
--Inserts to physical table work as expected
insert into tblTest (id) values (newid())
insert into tblTest (surname) values ('smith')
--Inserts into updateable view fail as no defaults are set
--from the underlying physical table
insert into vwTest (id) values (newid())
insert into vwTest (surname) values ('jones')
我看到有人在使用 INSTEAD OF INSERT 触发器中的默认值中有类似的东西,并通过将插入的行复制到临时表中然后更改临时表以添加物理表中的默认约束来解决它。我不确定我能否容忍这些额外步骤的性能问题。