I\'m having trouble understanding the difference between a stored procedure and a trigger in sql. If someone could be kind enough to explain it to me that would be great.
<If you are familiar with JavaScript, a trigger
is an addEventListener
and Stored Procedure
is a callback
.
Both are database objects containing blocks lof code that can be used for implementing business logic
The differences are:
1) Triggers
fire automatically but they need events for that.
(Example: create
,alter
,drop
,insert
,delete
,update
) .
2) Procedures have to be explicitly called and then executed.
They do not need create
,alter
,drop
,insert
,delete
,update
.
we can also execute procedures automatically using the sp_procoption.
3) we cannot pass parameters inside the triggers
,
example: if we want to display a message "error"
using a trigger: we need some DDL/DML
Statement
using a procedure: NO DDL/DML
is needed
A stored procedure can be called form another stored procedure but not ab trigger. A stored procedure can be executed whenever a user wants but not a trigger.A trigger is fired only when events occur. A stored procedure can have a print statement,multiple parameters and return values but not a trigger. A stored procedure can be called from front end but not trigger.
A stored procedure is a user defined piece of code written in the local version of PL/SQL, which may return a value (making it a function) that is invoked by calling it explicitly.
A trigger is a stored procedure that runs automatically when various events happen (eg update, insert, delete).
IMHO stored procedures are to be avoided unless absolutely required.
Difference Between a Stored Procedure and a Trigger
We can define a trigger as a database object just like a stored procedure, or we can say it is a special kind of stored procedure which fires when an event occurs in a database. We can execute a SQL query that will "do something" in a database when an event is fired.
Triggers are fired implicitly while stored procedures are fired explicitly.
A trigger is a special kind of stored procedure. It is attached to a table and only triggers when an insert, update or delete occurs. Stored procedures are essential functions that you can create and reuse in the table.