且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更新失败,因为子查询返回了多个值

更新时间:2023-11-23 07:54:22

触发器是根据声明执行的,而不是根据执行的,这就是错误的根源.您的触发器假定插入和删除的表将仅具有一行,但是那完全是错误的.
插入/删除表中的行数是DML语句(更新/插入/删除)影响的行数.

Triggers are executed per statement, not per row, that's the source of your error. Your trigger assumes that the inserted and deleted tables will only ever have one row, however that is simply wrong.
The number of rows in the inserted / deleted tables is the number of rows effected by the DML statement (update/insert/delete).

我不知道过程 calc_atten 做什么,但是您需要找到一种在设定级别而不是像现在那样在标量变量上执行它的逻辑的方法.

I don't know what the procedure calc_atten does, but you need to find a way to execute it's logic on a set level and not on scalar variables as it does now.

应更改触发器开头的条件以适合多行更新.一种实现方法是:(如果我知道表的结构,我可能会写得更短更好)

Your condition at the beginning of the trigger should be changed to fit a multi-row update. One way to do it is this: (I could probably write it shorter and better if I would have known the table's structure)

IF EXISTS (
    SELECT 1
    FROM deleted d 
    INNER JOIN inserted i
    ON d.[unique row identifier] = i.[unique row identifier]
    WHERE i.userId <> d.UserId
)

* [唯一行标识符]代表该表中每行唯一的任何列或列组合.如果唯一的行标识符包含UserId列,则它将无法正常工作.

*[unique row identifier] stands for any column or column combination that is unique per row in that table. If the unique row identifier contains the UserId column then this will not work properly.