2012-04-06 190 views
0

我想在SQL Server表上創建觸發器。在SQL Server表上創建觸發器

表有8列。其中之一是email。即[email protected]

我要的是:當一個新行插入表,觸發器應與msn.com

CREATE TRIGGER TIGUPDATEISP ON SUBS 
    FOR INSERT 
    AS 
    UPDATE SUBS 
    SET ISP = SELECT RIGHT(EMAIL, LEN(EMAIL) - CHARINDEX('@', EMAIL) FROM INSERTED) 

這是更新所有我isp與最後的值更新我的ISP列。但是,我想根據插入更新一個。

回答

2

如果ISP列允許空值

CREATE TRIGGER TIGUPDATEISP ON Subs 
    FOR INSERT 
AS 
BEGIN 

    SET NOCOUNT ON; 

    UPDATE SUBS 
     SET ISP = (SELECT RIGHT(EMAIL, LEN(EMAIL) - CHARINDEX('@', EMAIL)) 
     FROM INSERTED 
     WHERE SUBS.ID = INSERTED.ID) 
    FROM INSERTED 
    WHERE SUBS.Id = INSERTED.ID 

END 

這將工作,如果ISP列不允許使用NULL

CREATE TRIGGER TIGUPDATEISP ON Subs 
    INSTEAD OF INSERT 
AS 
BEGIN 

    SET NOCOUNT ON; 

    INSERT Subs (EMAIL, Isp) 
    SELECT EMAIL, RIGHT(EMAIL, LEN(EMAIL) - CHARINDEX('@', EMAIL)) FROM INSERTED 

END 
+0

天才這將工作。謝謝。 – Peter 2012-04-06 19:38:20