插入视图并使用基础表的默认值

时间:2016-05-24 07:47:24

标签: sql-server view sql-insert

我有一张桌子,例如Customers(CustomerType, Name)和每个客户类型的两个视图:

create view PremiumCustomers as
(
  select Name from Customers where CustomerType = 1
);

create view NormalCustomers as
(
  select Name from Customers where CustomerType = 2
);

我是否可以插入其中每个视图并相应地设置CustomerType的默认值?

e.g。使用:

INSERT INTO PremiumCustomers (name) VALUES ('foo')

('foo',2)插入Customers表。

1 个答案:

答案 0 :(得分:1)

试试这个

CREATE TRIGGER TrPremiumCustomersInsteadTrigger on PremiumCustomers
INSTEAD OF INSERT
AS
BEGIN
  INSERT INTO Customers (Name, CustomerType)
       SELECT Name, 1
       FROM inserted
END;


CREATE TRIGGER TrNormalCustomersInsteadTrigger on NormalCustomers 
INSTEAD OF INSERT
AS
BEGIN
  INSERT INTO Customers (Name, CustomerType)
       SELECT Name, 2
       FROM inserted
END;

INSERT INTO PremiumCustomers (name) VALUES ('foo')
INSERT INTO NormalCustomers (name) VALUES ('foo')