What are Triggers and Types of Triggers in SQL Server

In SQL Server, triggers are a type of stored procedure that automatically execute in response to specific data manipulation events, such as insert, update, or delete operations on a table. Triggers can be used to enforce data integrity rules, audit changes to the data, or perform complex business logic.

There are two types of triggers in SQL Server:

DML Triggers: 
These triggers fire in response to data manipulation language (DML) statements, such as INSERT, UPDATE, and DELETE. DML triggers can be defined to execute either before or after the DML statement.

DDL Triggers: 
These triggers fire in response to data definition language (DDL) statements, such as CREATE, ALTER, and DROP. DDL triggers can be defined to execute either before or after the DDL statement.

DML triggers can be further classified into two types based on when they fire:

  1. After Triggers: These triggers execute after the DML statement has completed, but before any constraints or referential integrity rules are enforced.
  2. Instead of Triggers: These triggers execute instead of the DML statement. They allow you to modify the data or perform custom business logic before the data is inserted, updated, or deleted.

Triggers can be defined at the table level or at the database level. When a trigger is defined at the table level, it only fires in response to data manipulation events on that table. When a trigger is defined at the database level, it fires in response to data manipulation events on any table in the database.

Here are a few examples of triggers in SQL Server:

Implementation as Audit Trigger: This trigger can be used to audit changes to a table. For example, suppose you have a table named "Employee" and you want to track changes to the "Salary" column. You can create a trigger that fires after an update to the "Salary" column and inserts a record into an audit table. 

Here's an example of the trigger:

CREATE TRIGGER Audit_Employee_Salary
ON Employee
AFTER UPDATE
AS
BEGIN
    INSERT INTO Employee_Audit (EmployeeID, OldSalary, NewSalary, ChangeDate)
    SELECT i.EmployeeID, d.Salary, i.Salary, GETDATE()
    FROM inserted i
    INNER JOIN deleted d ON i.EmployeeID = d.EmployeeID
END

Implementation as Constraint Trigger: This trigger can be used to enforce data integrity rules. For example, suppose you have a table named "Orders" and you want to ensure that the total amount of an order cannot exceed the customer's credit limit. You can create a trigger that fires before an insert or update to the "Orders" table and checks the customer's credit limit. 

Here's an example of the trigger:

CREATE TRIGGER Orders_CreditLimit
ON Orders
INSTEAD OF INSERT, UPDATE
AS
BEGIN
    IF EXISTS (
        SELECT *
        FROM inserted i
        INNER JOIN Customers c ON i.CustomerID = c.CustomerID
        WHERE i.TotalAmount > c.CreditLimit
    )
    BEGIN
        RAISERROR ('Total amount of the order exceeds the customer''s credit limit.', 16, 1)
        ROLLBACK TRANSACTION
        RETURN
    END

    INSERT INTO Orders (OrderID, CustomerID, OrderDate, TotalAmount)
    SELECT OrderID, CustomerID, OrderDate, TotalAmount
    FROM inserted
END

Note that these are just a few above examples of the types of triggers that can be created in SQL Server. The possibilities are endless, and triggers can be used to perform a wide range of tasks depending on your specific needs.

What are Advantages of using Stored procedure instead a Inline Query

Stored procedures and inline queries both serve the purpose of executing SQL statements, but they differ in several aspects.

A stored procedure is a pre-compiled program that is stored in a database and can be executed multiple times with different parameters. It can contain multiple SQL statements and can be called from various applications or client programs. Stored procedures can also be used to encapsulate complex business logic and rules, making it easier to maintain and update the code.

On the other hand, an inline query is a SQL statement that is included in the code of an application or a client program. It is compiled and executed every time it is called, which can result in performance issues for complex queries.

Here are some advantages of using stored procedures over inline queries:

Performance: 
Stored procedures are compiled once and stored in the database, which means that subsequent calls are faster than inline queries, as they don't need to be compiled each time. This can result in significant performance improvements, especially for complex queries.

Security: 
Stored procedures can be used to control access to the database by granting specific permissions to users or roles. This allows you to limit the actions that can be performed on the database, making it more secure.

Encapsulation: 
Stored procedures can encapsulate complex business logic, making it easier to maintain and update the code. This also allows developers to reuse code across multiple applications, reducing development time and improving code quality.

Debugging: 
Stored procedures can be debugged using SQL Server Management Studio or other debugging tools, which can make it easier to identify and fix issues.

Overall, stored procedures provide a more secure, efficient, and maintainable way of executing SQL statements, particularly for complex queries or those that are frequently used.




What is Difference in Primary Key and Unique Key

Both Primary Key and Unique Key are used to enforce uniqueness of a column or a group of columns in a database table. However, there are some differences between them.

Primary Key:
A primary key is a column or a combination of columns that uniquely identify a record in a table. It cannot contain null values and there can be only one primary key per table. The primary key is automatically indexed by the database and is used as a foreign key in related tables to establish relationships between them.

Unique Key:
A unique key is a column or a combination of columns that must have unique values. Unlike primary keys, it can contain null values but there can be more than one unique key per table. A unique key is used to enforce the integrity of the data and ensure that there are no duplicate values in the table.

In summary, the main differences between Primary Key and Unique Key are:
  • A table can have only one primary key, but can have multiple unique keys.
  • A primary key cannot contain null values, but a unique key can contain null values.
  • A primary key is used as a foreign key in other tables to establish relationships, while a unique key is used to enforce the integrity of the data and ensure that there are no duplicate values.
Both Primary Key and Unique Key are important in ensuring data integrity and should be carefully chosen based on the specific requirements of the database design.