What is the difference between a trigger and a stored procedure?

A trigger is a block of code that is executed automatically when a specific event occurs in a database, such as when a record is inserted, updated, or deleted. Triggers are often used to implement complex business rules, maintain data integrity, or audit changes to data.

Example of a Trigger:
CREATE TRIGGER tr_Employee_Update
ON Employee
AFTER UPDATE
AS
BEGIN
UPDATE Employee
SET LastUpdated = GETDATE()
WHERE EmployeeID =
(SELECT EmployeeID FROM deleted)
END

A stored procedure is a precompiled set of SQL statements that can be executed multiple times with different parameters. Stored procedures are often used to encapsulate complex business logic and are used to improve application performance by reducing the amount of code that needs to be executed.

Example of a Stored Procedure:
CREATE PROCEDURE GetEmployeeInfo
@EmployeeID int
AS
BEGIN
SELECT *
FROM Employee
WHERE EmployeeID = @EmployeeID
END

What is the main purpose of a stored procedure?

The main purpose of a stored procedure is to allow for efficient reuse of code. It is a set of SQL statements that are stored in the database and can be called from other programs or applications.

For example, a stored procedure might be used to retrieve customer information from a database. The stored procedure can then be called from a web page, allowing the web page to display customer information without having to write the same code multiple times.

What is the purpose of a stored procedure?

A stored procedure is a set of SQL statements that can be stored in a database and reused as a single unit. It is commonly used to encapsulate a set of operations that can be used over and over again in multiple contexts.

For example, a stored procedure could be used to insert data into a table. This procedure could be used every time new data needs to be added to the table, without having to write the same code over and over again. The procedure could be called with a single line of code, which would then execute all the necessary steps to insert the data.