tags:

views:

729

answers:

5

I've been hearing about triggers, and I have a few questions.
What are triggers?
How do I set them up?
Are there any precautions, aside from typical SQL stuff, that should be taken?

A: 

A trigger is a named database object that is associated with a table and that is activated when a particular event occurs for the table.

To create a trigger:

CREATE TRIGGER triggerName [BEFORE|AFTER] [INSERT|UPDATE|DELETE|REPLACE] ON tableName FOR EACH ROW SET stuffToDoHERE;


Even though I answered this part the other question still stands.

Unkwntech
+1  A: 

From dev.mysql.com, a trigger is

...a named database object that is associated with a table and that is activated when a particular event occurs for the table.

The syntax to create them is also documented at that site.

Briefly,

CREATE
    [DEFINER = { user | CURRENT_USER }]
    TRIGGER trigger_name trigger_time trigger_event
    ON tbl_name FOR EACH ROW trigger_stmt

And they provide an example:

CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;

You at least need to abide by all the restrictions on stored functions. You won't be able to lock tables, alter views, or modify the table that triggered the trigger. Also triggers may cause replication problems.

Blair Conrad
+11  A: 

Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table).

I can't comment on mysql specifically.

Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't).

Some things I'd still use triggers for

  • Keeping track of "date_created" and "date_last_edited" fields
  • Inserting "ID"'s (in oracle, where there is no auto id field)
  • Keeping change history

Things you wouldn't want to use triggers for

  • business rules/logic
  • anything which connects outside of the database (eg a webservice call)
  • Access control
  • Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction )
Matthew Watson
A: 

What are some good and not so good ways to use triggers?

Unkwntech
A: 

How do you create a trigger for event of accessing a table ? mytable has field 'view_count', each time this table is accessed for matching 'id' I want to increment the 'view_count'?