Share via


How to: Create Triggers

You can create triggers using the Table Designer or the CREATE TRIGGER command. For each table, you can create one trigger for each of the three events: INSERT, UPDATE, and DELETE. A table can have a maximum of three triggers at any one time.

To create a trigger

For example, perhaps each time Tasmanian Traders sells an item, they want to compare the remaining Units_in_stock against the Reorder_level and be notified if they need to reorder that item. You can create an Update trigger on the products table to accomplish this. Every time a product is sold, the Update trigger will fire and the Units_in_stock fieldwill be updated to reflect the remaining items in stock.

To create the trigger, you can specify updProductsTrigger( ) as your Update trigger for the products table. You can add a field to products, named reorder_amount, which stores the amount you want to order each time you reorder the item, and create a reorder table with the fields: product_id and reorder_amount. You can then add this code to your stored procedure:

PROCEDURE updProductsTrigger
   IF (units_in_stock+units_on_order) <= reorder_level
   INSERT INTO Reorder VALUES(Products.product_id, ;
    Products.reorder_amount)
   ENDIF   
ENDPROC

You can create similar triggers for an insert or delete event by using the FOR INSERT or FOR DELETE clause, respectively, instead of the FOR UPDATE clause. If you attempt to create a trigger that already exists for a particular event and table while SET SAFETY Command is on, Visual FoxPro prompts you to confirm overwriting the existing trigger.

Note

When a trigger is called, the Alias is always that of the cursor being updated, regardless of the Alias selected in the code that caused the trigger to fire.

Visual FoxPro includes the Referential Integrity Builder to generate triggers and stored procedures that enforce Referential Integrity (RI) rules for your database. For more information on using the RI Builder, see Referential Integrity Builder and How to: Build Referential Integrity Between Tables.

See Also

Tasks

How to: Edit Table Structure

How to: Modify Triggers (Visual FoxPro)

Concepts

Trigger Usage

Other Resources

Working with Tables (Visual FoxPro)