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.
<
In respect to triggers in SQL Server: a trigger is a special piece of code that automatically gets executed when an event occurs in the database server.
DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected
We can create trigger like this:
CREATE TRIGGER TriggerName
ON [dbo].[TableName]
FOR DELETE, INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
END
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
We can create a stored procedure like this:
CREATE PROCEDURE dbo.Sample_Procedure
@param1 int = 0,
@param2 int
AS
SELECT @param1,@param2
RETURN 0;
Differences in both of then
Trigger can not be called manually where stored procedure can be called manually.
Trigger executes automatically when event happens and can be use for reporting and data protection from deleting or dropping the table and data from database. We can prevent from trigger. On the other hand, a stored procedure has to be called by somebody.
A stored procedure can be called from front end (client application) but trigger can not be called from client application.