我有两种形式,即frmSupplier
和frmCustomer
,允许用户添加和更新客户和供应商信息。目前,我们在Customer
和Supplier
的SQL Server数据库中有两个表。我们正在将这两个表迁移到一个名为Contact
的表中,并将Customer
和Supplier
表转换为视图。我们这样做是因为我们希望我们的应用程序中的代码不再被修改,因为这需要时间。
我做了研究,发现了INSTEAD OF INSERT
个触发器。
这是SQL:
CREATE TABLE [dbo].[Contact]
(
[ContactID] [int] IDENTITY(1,1) NOT NULL,
[Code] [varchar](20) NULL,
[ContactName] [varchar](52) NULL,
[Active] [bit] NULL,
[Customer] [bit] NULL,
[Supplier] [bit] NULL,
[DeliveryAddr1] [varchar](255) NULL,
[DeliveryAddr2] [varchar](75) NULL,
[DeliveryAddr3] [varchar](75) NULL,
[DeliveryAddr4] [varchar](75) NULL,
[CreateDate] [datetime] NULL,
[LastUpdated] [datetime] NULL,
[TempID] [int] NULL,
CONSTRAINT [PK_Contact]
PRIMARY KEY CLUSTERED ([ContactID] ASC)
) ON [PRIMARY]
GO
为客户创建视图:
CREATE VIEW [dbo].[Customer]
AS
SELECT
ContactID AS CustID, Code AS CustCode,
ContactName AS CustName, Active, Customer,
DeliveryAddr1, DeliveryAddr2, DeliveryAddr3, DeliveryAddr4,
CreateDate, LastUpdated
FROM
dbo.Contact
WHERE
(Customer = 1)
GO
供应商视图:
CREATE VIEW [dbo].[Supplier]
AS
SELECT
ContactID AS SuppID, Code AS SuppCode,
ContactName AS SuppName, Active,
DeliveryAddr1, DeliveryAddr2, DeliveryAddr3, DeliveryAddr4,
CreateDate, LastUpdated
FROM
dbo.Contact
WHERE
(Supplier = 1)
我希望在插入供应商时,它会将其插入Contact
并设置Supplier=1
,或者如果插入了客户,则会设置Customer=1
。
这是我的触发器:
CREATE TRIGGER trgNewCust
ON dbo.Contact
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO Customer
SELECT
[CustCode], [CustName], [Active],
[DeliveryAddr1], [DeliveryAddr2], [DeliveryAddr3], [DeliveryAddr4]
FROM
inserted
END
我将在哪里设置Customer=1
或Supplier=1
?另一个问题是我如何知道Contact
中新插入的项目是供应商还是客户?
值为客户使用INSERT INTO Customer...
和供应商使用INSERT INTO Supplier...
插入C#应用程序。
答案 0 :(得分:2)
您需要在VIEWS上使用INSTEAD OF INSERT
触发器 - 而不是Contact
表!
CREATE TRIGGER trgNewCust
ON dbo.Customer -- trigger must be on the VIEW - not the underlying table!
INSTEAD OF INSERT
AS
BEGIN
-- *ALWAYS* explicitly define the list of columns you're inserting into!
INSERT INTO Contact(Code, ContactName, Active, Customer, Supplier,
DeliveryAddr1, DeliveryAddr2, DeliveryAddr3, DeliveryAddr4)
SELECT
CustCode, CustName, Active, 1, 0,
DeliveryAddr1, DeliveryAddr2, DeliveryAddr3, DeliveryAddr4
FROM
inserted
END
所以在这里,在Customer
视图的触发器中,设置Customer=1, Supplier=0
- 您将相同的触发逻辑应用于Supplier
视图并将数据插入Contact
} table,设置Customer=0, Supplier=1
现在,从您的代码中,如果您在Customers
视图中“插入”某些内容,则会在dbo.Contact
表中创建一行,并且当您“插入”{时{1}}查看。