2012-10-28 14 views
0

我有一個可更新的視圖使用而不是觸發器插入/更新。該觸發器使用合併。我發現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') 

我看到有人有類似的東西在Using default values in an INSTEAD OF INSERT trigger並通過插入一個臨時複製行,然後改變臨時表,以從默認的限制添加解決它物理表。我不確定我能否容忍這些額外步驟的性能問題。

+0

我改變了我的觸發器代碼,使用「Insert into tblTest Select * from Inserted」來處理插入操作 - 同樣的問題。我開始認爲我在這裏錯過了一些基本的東西。 – winnt93

回答

1

夠簡單。爲了使用默認值,您必須使用DEFAULT關鍵字,或者不要將其包含在插入內容中。即使是NULL值也是如此。在這種情況下,您需要在觸發器的插入中指定值。如果你是它的一部分從

When Not Matched By Target Then 
Insert 
(
    id, 
    forename, 
    surname 

) 
Values 
(
    i.id, 
    i.forename, 
    i.surname 

) 

改變

When Not Matched By Target Then 
Insert 
(
    id, 
    forename, 
    surname 

) 
Values 
(
    i.id, 
    i.forename, 
    DEFAULT 

) 

你會看到姓的默認值開始出現。不幸的是,這並不能真正幫助你做什麼。我能想到的最好的解決方案(並不是很好)是使用isnulls將你的默認值放入觸發器。

When Not Matched By Target Then 
Insert 
(
    id, 
    forename, 
    surname 

) 
Values 
(
    ISNULL(i.id,newid()), 
    i.forename, 
    ISNULL(i.surname,'xxyyzz') 

) 

我知道,從維護的角度來看這並不好,但它會起作用。如果您有興趣,我在DEFAULT關鍵字here上做了一篇文章,並附有大量的細節。

相關問題