这是我第一次处理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
我尝试创建此触发器,但却出现了这样的错误:
Msg 4104,Level 16,State 1,Procedure AntiCloneInsert,Line 6
无法绑定多部分标识符“NEW.item_type”。Msg 4104,Level 16,State 1,Procedure AntiCloneInsert,Line 8
无法绑定多部分标识符“NEW.item_type”。Msg 4104,Level 16,State 1,Procedure AntiCloneInsert,Line 8
无法绑定多部分标识符“NEW.warehouse”。Msg 4104,Level 16,State 1,Procedure AntiCloneInsert,Line 11
无法绑定多部分标识符“NEW.char_id”。
答案 0 :(得分:4)
SQL Server没有new
和old
记录。相反,它有inserted
和deleted
表。这意味着可以使用set操作(或循环,如果你真的喜欢)来完成逻辑。
我认为以下是等效的逻辑:
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