Convert Oracle SQL trigger into a SQL Server trigger

2g32fytz  于 12个月前  发布在  Oracle
关注(0)|答案(2)|浏览(226)

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.

pcrecxhr

pcrecxhr1#

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://learn.microsoft.com/en-us/sql/relational-databases/triggers/use-the-inserted-and-deleted-tables?view=sql-server-ver15

mf98qq94

mf98qq942#

Hello One way to convert from Oracle to Sql Server could be this:

CREATE TABLE AM_LABELS (
    LABEL_ID int PRIMARY KEY,
    LABEL_NAME NVARCHAR(50)
);

CREATE TABLE AM_LABEL_URLS (
    URL_ID int PRIMARY KEY,
    LABEL_ID int,
    URL NVARCHAR(200),
    FOREIGN KEY (LABEL_ID) REFERENCES AM_LABELS(LABEL_ID)
);

INSERT INTO AM_LABELS (LABEL_ID, LABEL_NAME) VALUES (1, 'Label 1');
INSERT INTO AM_LABELS (LABEL_ID, LABEL_NAME) VALUES (2, 'Label 2');

INSERT INTO AM_LABEL_URLS (URL_ID, LABEL_ID, URL) VALUES (101, 1, 'www.john1.com');
INSERT INTO AM_LABEL_URLS (URL_ID, LABEL_ID, URL) VALUES (102, 1, 'www.john2.com');
INSERT INTO AM_LABEL_URLS (URL_ID, LABEL_ID, URL) VALUES (103, 2, 'www.john3.com');

select * from AM_LABELS
select * from AM_LABEL_URLS

CREATE OR ALTER TRIGGER TRG_DEL_AM_LABELS
ON AM_LABELS
INSTEAD OF DELETE
AS
BEGIN
    DELETE FROM AM_LABEL_URLS WHERE LABEL_ID IN (SELECT deleted.LABEL_ID FROM deleted);
    DELETE FROM AM_LABELS WHERE LABEL_ID IN (SELECT deleted.LABEL_ID FROM deleted);
END;
GO

Test the trigger

DELETE FROM AM_LABELS 
WHERE LABEL_ID=2;

Hope it helps.

相关问题