SQL Server插入后触发器


10

我希望married在对marital_status列上的文本进行插入后触发该触发器,这是我到目前为止的结果

ALTER TRIGGER [dbo].[marriage]
ON  [dbo].[applicant_personal_info]
AFTER INSERT
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF (SELECT [marital_status] FROM inserted) = 'married'
 BEGIN
     INSERT INTO [dbo].[applicant_marriage_info]([dom])
     VALUES('abc')
 END
END

Answers:


11

您将在此处遇到的问题是由于SQL Server没有Oracle具有的“ FOR EACH ROW”触发器而引起的。您必须编写触发器来处理多行更改,即,INSERTED或DELETED虚拟表中可以包含多行。

如果要进行此类更新,则触发器将失败,因为(SELECT [marital_status] FROM inserted)它将返回多行,并且子查询必须返回单个值以用于直接比较。

触发器可能必须看起来像这样:

CREATE TRIGGER [dbo].[marriage] ON  [dbo].[applicant_personal_info] FOR INSERT
AS 
BEGIN
    SET NOCOUNT ON
    IF EXISTS (SELECT [marital_status] FROM INSERTED WHERE marital_status = 'married')
    BEGIN
        INSERT INTO [dbo].[applicant_marriage_info] ([dom])
        SELECT
            'abc' --Replace with whatever you're really inserting
        FROM INSERTED
        WHERE marital_status = 'married'
    END
END

8

因此,此触发器实际上非常接近您的需求。现在的问题是,如果插入了任何行,则仅一行会插入applicant_marriage_info。这是您真正想要的吗?如果一次插入多行会怎样?

ALTER TRIGGER [dbo].[marriage]
ON  [dbo].[applicant_personal_info]
AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    INSERT INTO [dbo].[applicant_marriage_info]([dom])
    SELECT 'abc' 
    FROM inserted 
    WHERE marital_status = 'married'
END

您可能需要比我显示的更多的列。


每次输入此数据均应完成
kabuto178

2
然后一种方法是用BEGIN INSERT INTO [dbo].[applicant_marriage_info]([dom]) SELECT 'abc' FROM inserted WHERE marital_status = 'married' END
–ypercubeᵀᴹ

为了说明这一点,我对示例代码做了一些更改。您不再需要IF EXISTS位。只需针对插入的查询运行查询并将该数据加载到另一个表中。您可能需要比我显示的更多的列,可能需要某种ID,但您可能会明白。
mrdenny
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.