Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Trigger question
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Stored procedures, Triggers, UDFs
Versions des environnements
SQL Server:
SQL Server 2000
Divers
Thread ID:
01500199
Message ID:
01500229
Vues:
51
>>>>Hello all, first things first - I have never used triggers. In a lot of my sp's I create a record of the current values of a table that I'm about to update along with the new values for the table - this makes it very easy for me to report on edits, is it possible to do this using a trigger ? A typical example of what I do is shown below
>>>>
>>>>
>>>>Proc UpdateAddress(@Addressid int,@line1 varchar(35),(@line2 varchar(35),
>>>>(@line3varchar(35),
>>>>(@line4 varchar(35))
>>>>As
>>>>Insert into AddressHistory
>>>>(Addressid int,
>>>>line1 ,
>>>>line2,
>>>>line3,
>>>>line4,
>>>>xline1,
>>>>xline2,
>>>>xline3,
>>>>xline4)
>>>>(Select
>>>>Addressid,
>>>>line1,
>>>>line2,
>>>>line3,
>>>>line4,
>>>>@line1,
>>>>@line2,
>>>>@line3,
>>>>@line4 from address where addressid = @Addressid  )
>>>>
>>>>-- Then update the address table with new values
>>>>
>>>>
>>>>
>>>>
>>>
>>>Try:
>>>
>>>CREATE TRIGGER ON  [dbo].[Address]
>>>       FOR UPDATE,INSERT
>>>AS
>>>BEGIN
>>>   *** Insert newly created records/UPDATEd in AddressHistory
>>>   INSERT INTO AddressHistory (Addressid,
>>>                               line1 ,
>>>                               line2,
>>>                               line3,
>>>                               line4,
>>>                               xline1,
>>>                               xline2,
>>>                               xline3,
>>>                               xline4)
>>>
>>>   SELECT AddressId,
>>>          line1 ,
>>>          line2,
>>>          line3,
>>>          line4,
>>>          ISNULL(DELETED.Line1,''),
>>>          ISNULL(DELETED.Line2,''),
>>>          ISNULL(DELETED.Line3,''),
>>>          ISNULL(DELETED.Line4,'')
>>>  FROM INSERTED 
>>>  LEFT JOIN DELETED ON INSERTED.AddressId = DELETED.AddressId
>>>END
>>>
>>>
>>>and you could try it:
>>>
>>>INSERT INTO Address .....
>>>UPDATE Address SET Line1 = 'asdasdasdas' WHERE AddressId = 123
>>>
>>
>>Thanks Boris, works like a charm - I actually also pull fields from related tables into the history table could I still do this in a trigger ?
>
>Both metatables INSERTED and DELETED has exactly the same structure as the table .
>So you can join them the same way you join the main table.

Don't think I can do this with a trigger Boris, In reality my sp receives a lot of parameters (which I left out for brevity) which are required to pull the data from related tables - still I've learn't a lot about triggers that I didn't know ! thanks for your time
Regards,
Peter J. Kane



Pete
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform