2014-06-17 73 views
-1

我想寫一個觸發器:如果在一個表中存在的記錄,更新另一個表,如果不存在插入到該表 我得到一個錯誤創建這個觸發器:多部分組成的標識符「插入的」無法綁定

CREATE TRIGGER TR_update_laststatus_on_membersservices ON [dbo].[activemembers] AFTER 
INSERT AS 
BEGIN 
IF EXISTS  
    (
    SELECT 1 
    FROM [membersservices] 
WHERE [membersservices].[mobilenumber] = INSERTED.[mobilenumber] 
    AND [membersservices].[sid] = INSERTED.[sid]  
)  
BEGIN 
    UPDATE membersservices 
    SET membersservices.[last_status] = INSERTED.enable 
    WHERE membersservices.mobilenumber=INSERTED.mobilenumber and membersservices.[sid]=INSERTED.[sid] 
END 
ELSE 
    INSERT INTO membersservices VALUES (INSERTED.[mobilenumber] ,INSERTED.[sid] ,INSERTED.[enable] , INSERTED.[dt]); 
end 
+0

有什麼錯誤? – Dhwani

+0

多部分標識符「INSERTED.mobilenumber」無法綁定 – mnshahab

回答

1

INSERTED是您必須加入或進行子查詢的表。請記住,您可以一次插入多於一行。

2

插入的(僞)表,所以它必須出現在FROM子句中,每次使用它的時候:

SELECT 1 
    FROM [membersservices] 
    JOIN INSERTED on ... <--- you're missing this 
WHERE [membersservices].[mobilenumber] = INSERTED.[mobilenumber] 
    AND [membersservices].[sid] = INSERTED.[sid] 


UPDATE membersservices 
SET membersservices.[last_status] = INSERTED.enable 
FROM membersservices  
JOIN INSERTED ON ... <-- you're missing this 


INSERT INTO membersservices (...) 
SELECT ... 
FROM INSERTED ... <-- you're missing this 

比你的邏輯下的併發其他不正確。您應該使用單個MERGE語句來執行更新和插入。

0

的問題是在你的INSERTED引用嘗試將其更改爲:

全部觸發:

CREATE TRIGGER TR_update_laststatus_on_membersservices 
       ON [dbo].[activemembers] AFTER INSERT AS 
BEGIN 
    IF EXISTS  
    (
     SELECT 1 
     FROM [membersservices] ms 
     JOIN INSERTED i ON ms.[mobilenumber] = i.[mobilenumber] 
         AND ms.[sid] = i.[sid]  
    )  
     BEGIN 
      UPDATE membersservices 
      SET membersservices.[last_status] = i.enable 
      FROM INSERTED i 
      WHERE membersservices.mobilenumber = i.mobilenumber 
       and membersservices.[sid] = i.[sid] 
     END 
    ELSE 
     INSERT INTO membersservices (mobilenumber, sid, enable, dt) 
     (SELECT mobilenumber, sid, enable, dt FROM INSERTED) 
END 
+0

如果你想要寫的'INSERT'語句行的'SELECT',用戶忽略'VALUES'和'()'與它相關聯。 –

+0

@Damien_The_Unbeliever謝謝你正忙於編輯它 – Tanner

+0

@ypercube謝謝,正在編輯它,因爲你評論 – Tanner

相關問題