0

我必须移植一个 PostgreSQL 触发器,但由于我没有太多经验,我不知道如何更改某些部分。原始触发器是:

CREATE TRIGGER aerolinea_tr
AFTER UPDATE
ON public.aerolinea FOR EACH ROW
EXECUTE PROCEDURE public."actualizaWarehoseTemplate"();

DECLARE
  mviews RECORD;
BEGIN
  IF (TG_OP = 'UPDATE') THEN
    FOR mviews  IN SELECT DISTINCT template.idtemplate
                    FROM template
                    INNER JOIN vueloaerolinea ON (template.idvueloaerolinea = vueloaerolinea.idvueloaerolinea)
                    WHERE vueloaerolinea.codigolinea = old.codigolinea
    LOOP
         UPDATE detalletemplate SET idwarehose = new.idwarehouse WHERE detalletemplate.idtemplate = mviews.idtemplate;
    END LOOP;
  END IF;
  RETURN old;
END;

我所做的是:

CREATE TRIGGER aerolinea_tr
ON aerolinea
AFTER UPDATE
AS
BEGIN
  -- if no row affected, the trigger ends.
  IF @@ROWCOUNT = 0
  BEGIN
    RETURN;
  END;

  IF EXISTS(SELECT * FROM inserted)
  BEGIN
    IF EXISTS(SELECT * FROM deleted)
    BEGIN
      --Update code goes here.
    END
  END
END;

但是我找不到与 SQL Server 的 RECORD 等效的东西,而且我不知道该怎么做。

4

1 回答 1

0

看起来您需要使用cursor。你可以尝试这样的事情——它不完整,因为我不知道 aerolinea 表的表模式,但尽管如此,应该让你朝着正确的方向前进:

DECLARE @idtemplate INT //Assuming this is an int
DECLARE @mviews CURSOR
DECLARE @newidwarehouse INT

SELECT @newidwarehouse = idwarehouse FROM INSERTED

SET @mviews = CURSOR FOR
SELECT DISTINCT template.idtemplate
FROM template
    INNER JOIN vueloaerolinea ON (template.idvueloaerolinea = vueloaerolinea.idvueloaerolinea)
    INNER JOIN DELETED ON DELETED.codigolinea = vueloaerolinea.codigolinea

OPEN @mviews 
FETCH NEXT
FROM @mviews INTO @idtemplate 
WHILE @@FETCH_STATUS = 0
BEGIN
    UPDATE detalletemplate
    SET idwarehose = @newidwarehouse 
    WHERE detalletemplate.idtemplate = @idtemplate 
FETCH NEXT
FROM @mviews INTO @idtemplate 
END
CLOSE @mviews 
DEALLOCATE @mviews 

顺便说一句,您在检查更新时不需要检查已插入和已删除。您只需检查已删除:

IF EXISTS (SELECT * FROM DELETED)
于 2013-01-08T05:06:21.410 回答