INSTEAD OF INSERT / UPDATE触发错误,“列名或提供的值数与表定义不匹配”

时间:2016-09-27 21:17:56

标签: sql sql-server triggers

在SQL Server中,我试图在视图上编写INSTEAD OF INSERT触发器,当通过MS Access编辑时,该触发器将改变多个表。我们的想法是为不存在的记录创建一个insert语句,并在找到关联的ID时进行更新。当我使用以下触发器时,它按预期工作......

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [ofs].[IO_Trig_OFS] 
ON [ofs].[V_OFS_CONTRACTORS]  
INSTEAD OF INSERT  
AS  
BEGIN  
    SET NOCOUNT ON  

    -- Check for duplicate Contact. If there is no duplicate, do an insert.  
    IF (NOT EXISTS (SELECT P.ContactID  
                    FROM [ofs].[OFS_CONTACTS] P, inserted I  
                    WHERE P.ContactID = I.ContactID))  
        INSERT INTO [ofs].[OFS_CONTACTS]  
            SELECT 
                [ContractorID],
                [ContactFirstName], [ContactLastName],
                [ContactPriority], [JobTitle],
                [EmailAddress], [WorkPhone], [WorkExtension],
                [CellPhone], [ContactSource]  
            FROM 
                inserted  
    ELSE  
        --If there is a duplicate, change to UPDATE so that there will not  
        --be a duplicate key violation error.  
        UPDATE [ofs].[OFS_CONTACTS]  
        SET [ContactFirstName] = I.ContactFirstName,
            [ContactLastName] = I.ContactLastName,
            [ContactPriority] = I.ContactPriority,
            [JobTitle] = I.JobTitle,
            [EmailAddress] = I.EmailAddress,
            [WorkPhone] = I.WorkPhone,
            [WorkExtension] = I.WorkExtension,
            [CellPhone] = I.CellPhone,
            [ContactSource] = I.ContactSource  
        FROM 
            [ofs].[OFS_CONTACTS] E, inserted I  
        WHERE 
            E.ContactID = I.ContactID  
END; 

但是当我以相同的方式添加另一个表来编辑插入/更新时,我得到了这个错误:

  

消息213,级别16,状态1,过程IO_Trig_OFS,第11行
  列名或提供的值数与表定义不匹配。

我觉得它的语法很差,但它有助于另外一套眼睛。谢谢!

0 个答案:

没有答案