无法将NULL值插入列错误

时间:2014-10-20 19:30:55

标签: triggers sql-server-2008-r2 null

我有一个问题,我想更新表中的列并使用触发器更新同一列但在另一个表中。它说我不能插入NULL,但我似乎无法理解从哪里得到NULL值。这是触发器:

CREATE TRIGGER Custom_WF_Update_WF_DefinitionSteps_DefinitionId ON WF.Definition 
AFTER UPDATE AS BEGIN 
IF UPDATE(DefinitionId) 
IF TRIGGER_NESTLEVEL() < 2 
BEGIN
    ALTER TABLE WF.DefinitionSteps NOCHECK CONSTRAINT ALL

    UPDATE WF.DefinitionSteps
    SET DefinitionId =
         (SELECT i.DefinitionId
          FROM inserted i,
               deleted d
          WHERE WF.DefinitionSteps.DefinitionId = d.DefinitionId
               AND i.oldPkCol = d.DefinitionId)
    WHERE WF.DefinitionSteps.DefinitionId IN
          (SELECT DefinitionId FROM deleted)

     ALTER TABLE WF.DefinitionSteps CHECK CONSTRAINT ALL 
END 
END

此更新声明可以正常工作:

UPDATE [CCHMergeIntermediate].[WF].[Definition] 
SET DefinitionId = source.DefinitionId + 445 
FROM [CCHMergeIntermediate].[WF].[Definition] source

但是这个失败了:

UPDATE [CCHMergeIntermediate].[WF].[Definition] 
SET DefinitionId = target.DefinitionId 
FROM [CCHMergeIntermediate].[WF].[Definition] source 
INNER JOIN [centralq3].[WF].[Definition] target 
ON (((source.Name = target.Name) OR (source.Name IS NULL AND target.Name IS NULL)))

我收到以下错误:

  

Msg 515,Level 16,State 2,Procedure Custom_WF_Update_WF_DefinitionSteps_DefinitionId,Line 7
  无法将值NULL插入列&#39; DefinitionId&#39;,table&#39; CCHMergeIntermediate.WF.DefinitionSteps&#39 ;;列不允许空值。更新失败。

如果我选择select而不是update语句,如下所示:

SELECT source.DefinitionId, target.DefinitionId
FROM [CCHMergeIntermediate].[WF].[Definition] source 
INNER JOIN [centralq3].[WF].[Definition] target 
ON (((source.Name = target.Name) OR (source.Name IS NULL AND target.Name IS NULL)))

我得到了这个结果: http://i.stack.imgur.com/3cZsM.png(对不起外部链接,我没有声望在这里发布图片)

我做错了什么?我不明白的是什么?我错过了什么..?

1 个答案:

答案 0 :(得分:0)

问题在于触发条件。我修改了从i.oldPkCol = d.DefinitionIdi.oldPkCol = **d.oldPkCol**的第二个位置并且它有效。

UPDATE WF.DefinitionSteps
SET DefinitionId =
     (SELECT i.DefinitionId
      FROM inserted i,
           deleted d
      WHERE WF.DefinitionSteps.DefinitionId = d.DefinitionId
           AND i.oldPkCol = **d.oldPkCol**)
WHERE WF.DefinitionSteps.DefinitionId IN
      (SELECT DefinitionId FROM deleted)