如何将以下oracle触发器转换为SQL Server触发器?

时间:2017-12-15 10:55:29

标签: sql-server tsql database-trigger

我想将Oracle数据库迁移到SQL Server。 我使用SQL Server迁移助手来转换数据库,但触发器无法正常工作。

如何将以下oracle触发器转换为SQL Server触发器?

create or replace TRIGGER "PEXLATEST".TRG_TCM_BEF_INS_UPD BEFORE INSERT OR UPDATE OR DELETE ON TYPE_CODE_MASTER REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
L_COUNT NUMBER:=0;
BEGIN
IF(INSERTING) THEN
  SELECT COUNT(1) INTO L_COUNT FROM TYPE_CODE_MASTER
  WHERE TCM_TYPE=:NEW.TCM_TYPE
  AND (TCM_NAME_E=:NEW.TCM_NAME_E OR TCM_NAME_A=:NEW.TCM_NAME_A);
  IF L_COUNT>0 THEN
     raise_application_error( -20001, 'Duplicate Name');
  END IF;
END IF;
IF (UPDATING) THEN
SELECT COUNT(1) INTO L_COUNT FROM TYPE_CODE_MASTER
  WHERE TCM_TYPE=:NEW.TCM_TYPE
  AND (TCM_NAME_E=:NEW.TCM_NAME_E OR TCM_NAME_A=:NEW.TCM_NAME_A)
  AND TCM_ID<>:NEW.TCM_ID;
  IF L_COUNT>0 THEN
     raise_application_error( -20001, 'Duplicate Name');
  END IF;
END IF;
IF (DELETING) THEN
IF :OLD.TCM_TYPE='ICTG' THEN
SELECT COUNT(1) INTO L_COUNT FROM ITEM
  WHERE ITM_CATEGORY_TYPE_ID=:OLD.TCM_ID;
  IF L_COUNT>0 THEN
     raise_application_error( -20002, 'Item Category referred in Items');
  END IF;
  END IF;
END IF;
END;

1 个答案:

答案 0 :(得分:1)

我很难检查我写的代码,但它可能是这样的:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [PEXLATEST].[TRG_TCM_BEF_INS_UPD]
   ON TYPE_CODE_MASTER
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
    SET NOCOUNT ON;


    IF EXISTS(SELECT 1 FROM inserted)
       BEGIN
            -- insert or update, check same condition in your code
            -- new rows are already inserted or updated because trigger execute always AFTER
            IF EXISTS(SELECT 1 FROM TYPE_CODE_MASTER 
                      WHERE TCM_TYPE IN (SELECT TCM_TYPE FROM inserted)
                      GROUP BY TCM_NAME_E
                      HAVING COUNT(*) > 1)
               OR EXISTS(SELECT 1 FROM TYPE_CODE_MASTER 
                        WHERE TCM_TYPE IN (SELECT TCM_TYPE FROM inserted)
                        GROUP BY TCM_NAME_A
                        HAVING COUNT(*) > 1)       

               BEGIN
                    RAISERROR('Duplicate Name', 16, 1);
                    ROLLBACK TRAN;
                    RETURN;
               END 
       END
    ELSE
       BEGIN
        -- delete
        IF EXISTS(SELECT 1 FROM deleted AS D
              INNER JOIN ITEM AS I ON I.ITM_CATEGORY_TYPE_ID = D.TCM_ID
              )
            BEGIN
                    RAISERROR('Item Category referred in Items', 16, 1);
                    ROLLBACK TRAN;
                    RETURN;
            END
       END
END
GO