2015-10-19 49 views
0

這是我第一次處理SQL Server觸發器。觸發器中的MySql的NEW.some_column的SQL Server模擬是什麼?

在此之前,我編寫了幾乎相同的觸發器爲MySql服務器,現在試圖重新編碼它的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 

我試圖創建這個觸發,但得到這樣的錯誤:

消息4104,級別16,狀態1,過程AntiCloneInsert,6號線
多部分標識符 「NEW.item_type」不能被綁定。

Msg 4104,Level 16,State 1,Procedure AntiCloneInsert,Line 8
無法綁定多部分標識符「NEW.item_type」。

消息4104,級別16,狀態1,過程AntiCloneInsert,第8行
無法綁定多部分標識符「NEW.warehouse」。

消息4104,級別16,狀態1,過程AntiCloneInsert,行11
無法綁定多部分標識符「NEW.char_id」。

回答

4

SQL Server沒有newold記錄。相反,它有inserteddeleted。這意味着可以使用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 
+0

謝謝。但你能再幫我一次嗎?我將這個觸發器發給了一些需要它的人,現在他告訴我們需要在'update'後添加額外的插入查詢來改進它。我不明白你的觸發器是如何工作的,不能修改它。 'insert into dbo.user_punish values($ char_id,1,0,NULL,DATEDIFF(s,'1970-01-01 00:00:00',GETUTCDATE()),NULL,getdate());' – Kosmos

+0

@Kosmos 。 。 。我不明白你的評論,我不會看到它與你的查詢有什麼關係(例如,表名是不同的)。也許你應該問另一個問題。 –

+0

我的意思是說,這個插入查詢應該與我的版本觸發器的'update'查詢一起執行,但是現在人告訴我,觸發器禁止每個玩家,所以它的邏輯有些問題。他現在試圖重新檢查禁止選手的規則。所以,再也不需要做任何事情了。謝謝。 – Kosmos