Marzo es el mes de la IA en Deztaca | Clase en vivo privada este sábado 28 de marzo de 2026. Clic aquí →

Respuestas 5

hace 1 año
Hola Pilar.
Te comparto un ejemplo del uso del Trigger. 
¨¨ Nota solo aplica para una sola tabla.

USE AdventureWorks2022;
GO
IF OBJECT_ID ('Purchasing.LowCredit','TR') IS NOT NULL
   DROP TRIGGER Purchasing.LowCredit;
GO
-- This trigger prevents a row from being inserted in the Purchasing.PurchaseOrderHeader table
-- when the credit rating of the specified vendor is set to 5 (below average).  
  
CREATE TRIGGER Purchasing.LowCredit ON Purchasing.PurchaseOrderHeader  
AFTER INSERT  
AS  
IF (ROWCOUNT_BIG() = 0)
RETURN;
IF EXISTS (SELECT 1  
           FROM inserted AS i   
           JOIN Purchasing.Vendor AS v   
           ON v.BusinessEntityID = i.VendorID  
           WHERE v.CreditRating = 5  
          )  
BEGIN  
RAISERROR ('A vendor''s credit rating is too low to accept new  
purchase orders.', 16, 1);  
ROLLBACK TRANSACTION;  
RETURN   
END;  
GO  
  
-- This statement attempts to insert a row into the PurchaseOrderHeader table  
-- for a vendor that has a below average credit rating.  
-- The AFTER INSERT trigger is fired and the INSERT transaction is rolled back.  
  
INSERT INTO Purchasing.PurchaseOrderHeader (RevisionNumber, Status, EmployeeID,  
VendorID, ShipMethodID, OrderDate, ShipDate, SubTotal, TaxAmt, Freight)  
VALUES (  
2  
,3  
,261  
,1652  
,4  
,GETDATE()  
,GETDATE()  
,44594.55  
,3567.564  
,1114.8638 );  
GO
hace 1 año
Gracias, José Caballero. Lo reviso y te comento.
Saludos
hace 1 año
Si alguien más me echa una mano, necesito guardar información en la Tabla 2, en cuanto se ingresen los datos en la Tabla 1.
Gracias de antemano.
Saludos
hace 1 año
Este ejemplo ya esta probado para que tengas un idea más puntual como aplicarlo a tus requerimientos.


------    Crear la tabla xproducto y la tabla xregistro_producto si no existen: 


CREATE TABLE xproducto (
    id_producto INT PRIMARY KEY,
    seccio NVARCHAR(100),
    nombre_producto NVARCHAR(100),
    precio DECIMAL(10, 2),
    fecha_recibido DATE,
    importado BIT,
    pais_origen NVARCHAR(100)
);

CREATE TABLE xregistro_producto (
    id_producto INT,
    nombre_producto NVARCHAR(100),
    precio DECIMAL(10, 2),
    INSERTADO DATETIME
);

------      Crear el trigger: 

CREATE TRIGGER trg_after_insert_xproducto
ON xproducto
AFTER INSERT
AS
BEGIN
    -- Insertar registros en la tabla xregistro_producto
    INSERT INTO xregistro_producto (id_producto, nombre_producto, precio, INSERTADO)
    SELECT 
        id_producto,
        nombre_producto,
        precio,
        GETDATE() -- Obtiene la fecha y hora actual
    FROM inserted;
END;

------ 
Explicación general:
  • CREATE TRIGGER trg_after_insert_xproducto ON xproducto AFTER INSERT: Crea un trigger llamado trg_after_insert_xproducto que se ejecuta después de que se inserten registros en la tabla xproducto.
  • BEGIN ... END: El bloque de código que se ejecuta cuando se activa el trigger.
  • INSERT INTO xregistro_producto ... SELECT ... FROM inserted; Inserta los datos en la tabla xregistro_producto seleccionando los valores de la tabla inserted. La tabla inserted es una tabla especial que contiene las filas que se acaban de insertar en xproducto.
  • GETDATE(): Función que devuelve la fecha y hora actual, que se usa para rellenar el campo INSERTADO.
Uso del Trigger:
Cada vez que se inserte un registro en la tabla xproducto, este trigger se activará automáticamente y copiará los datos correspondientes a la tabla xregistro_producto, junto con la fecha y hora de inserción.
Por ejemplo, si insertas un registro en xproducto como este:

--- se insertan los datos.

INSERT INTO xproducto (id_producto, seccio, nombre_producto, precio, fecha_recibido, importado, pais_origen)
VALUES (1, 'A', 'Producto 1', 100.00, '2024-06-14', 0, 'Perú');


----  se consulta:
SELECT * FROM xregistro_producto;

Resultado obtenido
 id_producto    nombre_producto    precio      INSERTADO
       
1                         | Producto 1                    | 100.00 |    2024-06-14 12:34:56.789 

EXITO




hace 1 año
Muchas gracias, José.
Saludos

Es necesario estar inscrito para dejar tu duda, comentario y/o respuesta.