简体   繁体   English

如何处理SQL Server中多行插入的插入触发器?

[英]How to handle insert triggers for multi-row inserts in SQL Server?

I have the following trigger: 我有以下触发器:

CREATE TRIGGER trigger_insert_student_table ON student_table
FOR INSERT
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @insertedStudentName VARCHAR(256);
    DECLARE @insertedMajor VARCHAR(256);
    DECLARE @insertedGrade VARCHAR(256);


    SET @insertedStudentName = (SELECT STUDENT_NAME FROM inserted);
    SET @insertedMajor = (SELECT MAJOR FROM inserted);
    SET @insertedGrade = (SELECT GRADE FROM inserted);

    IF (@insertedMajor='Economics' AND @insertedGrade = 'A')
    BEGIN
        /* DO SOME ACTION*/
    END

    ELSE IF(@insertedMajor='History' AND @insertedGrade = 'A')
    BEGIN
        /* DO SOME ACTION*/
    END
END

It works fine for single inserts, but when I do multi-row inserts it fails with the following error: 它适合单次插入,但是当我执行多行插入时,它失败并显示以下错误:

Subquery returned more than 1 value. 子查询返回的值超过1。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

How can I iterate through each inserted row and handle the actions? 如何遍历每个插入的行并处理操作?

Don't iterate. 不要迭代。 As soon as you find yourself saying "how do iterate" in SQL, you're doing it wrong. 一旦发现自己在SQL中说“如何进行迭代”,就错了。 Instead of setting these values to variables, think set based operations instead. 不要将这些值设置为变量,而应考虑基于集合的操作。 Think along the lines of "where inserted.Major = 'History' and inserted.Grade = 'A'. 按照“插入位置。主要='历史'和插入位置。等级='A”的思路思考。

I don't know what the "some action" is that you want to do here, but here's a simple example: 我不知道您要在此处执行的“某些操作”是什么,但这是一个简单的示例:

update t
set UpdateDate = getdate(),
    isStarEconomicsStudent = 1
from somePresentationTable a
inner join inserted i
    on a.StudentID = i.StudentID
        and i.Major = 'Economics'
        and i.Grade = 'A'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM