Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
How can I do this trigger?
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Divers
Thread ID:
01044125
Message ID:
01044168
Vues:
9
Try
CREATE TRIGGER utr_Detalle_Insert
ON Detalle
FOR INSERT 
AS 
BEGIN
	INSERT INTO Balance (Cuenta, Periodo, Fiscal, Balance)
		SELECT Cuenta, Periodo, Fiscal, 0 FROM INSERTED 
			WHERE NOT EXISTS( SELECT * FROM Balance 
					WHERE Balance.Cuenta = INSERTED.Cuenta
						AND Balance.Periodo = INSERTED.Periodo 
						AND Balance.Fiscal = INSERTED.Fiscal)

	UPDATE Balance
		SET Balance = Balance + INSERTED.Credito - INSERTED.Debito
	FROM Balance
	JOIN INSERTED ON Balance.Cuenta = INSERTED.Cuenta
		AND Balance.Periodo = INSERTED.Periodo 
		AND Balance.Fiscal = INSERTED.Fiscal

END
GO
>Hello everybody! I want to make a trigger that conditionally updates a table from another table. The structures are the following:
>
>
>** Detalle
>Cuenta  nVarchar(20)
>Periodo Int
>Fiscal  nvarchar(4)
>Debito  Money
>Credito Money
>
>
>And the updated table is:
>
>** Balance
>Cuenta  nVarchar(20)
>Periodo I
>Fiscal  nVarchar(4)
>Balance Money
>
>
>Now I want that everytime a record is added to Detalle the value of debito is added and the value of credito is substracted to/from Balance for the cuenta,Periodo and fiscal fields corresponding to the inserted record in the Detalle table. I know how to do that but I want the trigger to check when a corresponding record already exist and updates the data accordingly, if the record doesn't exist I want it to be added to Balance.
>
>
--sb--
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform