简体   繁体   中英

Convert Oracle SQL trigger into a SQL Server trigger

I have tried converting trigger written in Oracle to SQL Server triggers. But it does not allow to use table aliases and ":OLD" keyword in the query. Any idea how to do the correct conversion?

Oracle trigger:

   CREATE OR REPLACE TRIGGER TRG_DEL_AM_LABELS   BEFORE DELETE on AM_LABELS
    FOR EACH ROW 
       BEGIN
         DELETE FROM AM_LABEL_URLS ALU WHERE ALU.LABEL_ID = :OLD.LABEL_ID;
       END;

Converted SQL Server trigger:

CREATE OR ALTER TRIGGER TRG_DEL_AM_LABELS 
ON AM_LABELS    
INSTEAD OF DELETE
AS 
BEGIN
    DELETE FROM AM_LABEL_URLS ALU 
    WHERE ALU.LABEL_ID = :OLD.LABEL_ID;
END

CLOSE DELETED_CUR;
DEALLOCATE DELETED_CUR;
DELETE FROM AM_LABELS WHERE (.LABEL_ID;) IN (SELECT .LABEL_ID; FROM DELETED); 
;

These are the errors that popped up.

Incorrect syntax near ':'.

Incorrect syntax near 'ALU'.

But as it provided in documentation this query is valid to be used in SQL Server.

Use the DELETED table to access the old values:

DML trigger statements use two special tables: the deleted table and the inserted tables. SQL Server automatically creates and manages these tables. You can use these temporary, memory-resident tables to test the effects of certain data modifications and to set conditions for DML trigger actions.

The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows in common.

See https://docs.microsoft.com/en-us/sql/relational-databases/triggers/use-the-inserted-and-deleted-tables?view=sql-server-ver15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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