SQL触发器根据特定字段的更新在第二个table中插入记录
MSQL trigger to insert record in second table based on update of specific field
我需要在 Microsoft SQL 服务器中编写一个简单的触发器。涉及两个表(语法不规范请见谅):
customer {
customerno (integer)
comm_preference (varchar(1))
email (varchar(255))
}
email_sent {
customerno (integer)
email (varchar(255))
date (datetime)
}
customer.comm_preference 的有效值为 M、E、B(手机、电子邮件、两者)。我需要一个触发器,如果值更改为 E 或 B,则将带有 customer.customerno、customer.email 和今天日期的记录插入 email_sent。
到目前为止,我的努力已经白费了。有人可以帮助我吗?
试试这个,它会在 email_sent table 中插入一条新记录,同时记录插入 'E' 或 'B' 或值更改为 'E' 或'B'
CREATE TRIGGER dbo.trg
ON customer
AFTER INSERT,UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM inserted WHERE comm_preference IN ('E', 'B')
BEGIN
INSERT INTO email_sent
SELECT customerno, email, GETDATE() from inserted
END
END
尝试这样的事情;
CREATE TRIGGER trgCustomer_Update ON dbo.customer FOR UPDATE
AS
BEGIN
IF UPDATE(comm_preference)
BEGIN
INSERT dbo.email_sent
( customerno
,email
,date
)
SELECT i.customerno
,i.email
,GETDATE()
FROM inserted i
INNER JOIN deleted d
ON i.customerno = d.customerno
WHERE d.comm_preference NOT IN ( 'E', 'B' ) AND
i.comm_preference IN ( 'E', 'B' )
END
END
GO
此致,
里斯
我需要在 Microsoft SQL 服务器中编写一个简单的触发器。涉及两个表(语法不规范请见谅):
customer {
customerno (integer)
comm_preference (varchar(1))
email (varchar(255))
}
email_sent {
customerno (integer)
email (varchar(255))
date (datetime)
}
customer.comm_preference 的有效值为 M、E、B(手机、电子邮件、两者)。我需要一个触发器,如果值更改为 E 或 B,则将带有 customer.customerno、customer.email 和今天日期的记录插入 email_sent。
到目前为止,我的努力已经白费了。有人可以帮助我吗?
试试这个,它会在 email_sent table 中插入一条新记录,同时记录插入 'E' 或 'B' 或值更改为 'E' 或'B'
CREATE TRIGGER dbo.trg
ON customer
AFTER INSERT,UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM inserted WHERE comm_preference IN ('E', 'B')
BEGIN
INSERT INTO email_sent
SELECT customerno, email, GETDATE() from inserted
END
END
尝试这样的事情;
CREATE TRIGGER trgCustomer_Update ON dbo.customer FOR UPDATE
AS
BEGIN
IF UPDATE(comm_preference)
BEGIN
INSERT dbo.email_sent
( customerno
,email
,date
)
SELECT i.customerno
,i.email
,GETDATE()
FROM inserted i
INNER JOIN deleted d
ON i.customerno = d.customerno
WHERE d.comm_preference NOT IN ( 'E', 'B' ) AND
i.comm_preference IN ( 'E', 'B' )
END
END
GO
此致,
里斯