触发器中 MySql 的 NEW.some_column 的 SQL Server 模拟是什么?

Kos*_*mos 1 mysql sql sql-server

这是我第一次处理 SQL Server 触发器。

在此之前,我为 MySql Server 编写了几乎相同的触发器,现在尝试为 SQL Server 重新编码。我修复了所有东西,但现在不明白它想要什么?我们如何才能像在 MySQL 中那样访问刚刚插入的行的某些列 - NEW.some_field?

CREATE TRIGGER AntiCloneInsert ON dbo.user_item FOR INSERT AS

DECLARE @acc_id INT;
DECLARE @items_count INT;

IF (NEW.item_type in (select item_type from dbo.forbidden_item_types))
BEGIN
    select @items_count = count(item_type) from dbo.user_item where item_type = NEW.item_type and warehouse = NEW.warehouse
    IF (@items_count > 1)
    BEGIN
        select @acc_id = account_id from dbo.user_data where char_id = NEW.char_id
        update lin2db.dbo.user_account set block_flag2 = 1 where uid = @acc_id
    END
END
Run Code Online (Sandbox Code Playgroud)

我尝试创建此触发器但收到此类错误:

消息 4104,级别 16,状态 1,过程 AntiCloneInsert,第 6 行
无法绑定多部分标识符“NEW.item_type”。

消息 4104,级别 16,状态 1,过程 AntiCloneInsert,第 8 行
无法绑定多部分标识符“NEW.item_type”。

消息 4104,级别 16,状态 1,过程 AntiCloneInsert,第 8 行
无法绑定多部分标识符“NEW.warehouse”。

消息 4104,级别 16,状态 1,过程 AntiCloneInsert,第 11 行
无法绑定多部分标识符“NEW.char_id”。

Gor*_*off 5

SQL Server 没有newold 记录。相反,它有inserteddeleted 。这意味着可以使用集合操作(​​或循环,如果您真的喜欢)来完成逻辑。

我认为以下是等效的逻辑:

CREATE TRIGGER AntiCloneInsert ON dbo.user_item FOR INSERT AS
BEGIN   
    update ua
        set block_flag2 = 1
        from ua join
             dbo.user_data ud
             on ua.uid = ud.account_id join
             inserted i
             on ud.char_id = i.char_id join
             dbo.forbidden_item_types it
             on it.item_type = i.item_type
         where  (select count(it2.item_type)
                 from dbo.user_item it2
                 where it2.item_type = i.item_type and
                       it2.warehouse = i.warehouse
                ) > 1;
END
Run Code Online (Sandbox Code Playgroud)