2014-10-20 55 views
0

我遇到了一個問題,我想更新表中的列,並使用觸發器更新相同的列,但在另一個表中。它說我不能插入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
Cannot insert the value NULL into column 'DefinitionId', table 'CCHMergeIntermediate.WF.DefinitionSteps'; column does not allow nulls. UPDATE fails.

如果我做了select而不是upd吃了聲明,就像這樣:

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(對不起,外部鏈接,我沒有enaugh聲譽張貼在這裏的圖像)

我在做什麼錯?我沒有看到?我錯過了什麼?

回答

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)