Triggers in SQL Server

A trigger in SQL Server is a special kind of stored procedure that automatically executes when an event occurs in the database server. There are following types of triggers available in SQL Server,

  • DML Triggers
  • DDL Triggers
  • Logon Triggers

DML Triggers: DML Triggers get executed when a user tries to modify data through data manipulation language (DML) like INSERT, UPDATE, or DELETE statements on a table or view. DML triggers fire when any valid event is performed, regardless of whether or not any table rows are affected.

Example: 

CREATE TRIGGER d2c_trgInsertAuditInfo ON d2c_tblStudents AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
declare @studentName varchar(100)
select @studentName=tmp.studentName from INSERTED tmp
insert into d2c_tblStudentsAuditInfo
(auditInfo)
VALUES('New record inserted Student Name: '+@studentName+')
END

Explanation:
In above example we have created d2c_trgInsertAuditInfo trigger on d2c_tblStudents table.
Whenever any new record will insert into d2c_tblStudents table, d2c_trgInsertAuditInfo trigger
will fire and mentioned query will execute.

DDL Triggers:DDL triggers fire in response to a variety of Data Definition Language (DDL) events. These events primarily correspond to Transact-SQL statements that start with the keywords CREATE, ALTER, DROP, GRANT, DENY, REVOKE or UPDATE STATISTICS.Real word use of DDL Triggers is to track database changes or all database in server.

Example:

CREATE TRIGGER d2c_trgDatabaseChange ON ALL SERVER FOR CREATE_DATABASE
AS
BEGIN
SET NOCOUNT ON;
PRINT 'Database Created...'
END

Explanation:
In above example we have created d2c_trgDatabaseChange trigger on all server for creation of new database.Whenever any new database will create in server, d2c_trgDatabaseChange trigger will fire and mentioned query will execute.

Logon Triggers: Logon Triggers get executed in response to the LOGON event that is raised when a user sessions is being established. These are useful in cases where we want to track which all users are connecting to the SQL Server instance and and write that information in to a table which can be later used to review. General use is for auditing purposes and sometimes to prevent actions when login happens from a suspicious computer.

Example:

/* Create Audit Database */
CREATE DATABASE d2c_AuditDb
GO
USE d2c_AuditDb
GO
/* Create Audit Table */
CREATE TABLE d2c_ServerLogonLog
(SystemUser VARCHAR(512),DBUser VARCHAR(512),SPID INT,LogonTime DATETIME)
GO
/* Create Logon Trigger */
CREATE TRIGGER d2c_trgServerLogon ON ALL SERVER FOR LOGON
AS
BEGIN
INSERT INTO d2c_AuditDb.dbo.d2c_ServerLogonLog
SELECT SYSTEM_USER,USER,@@SPID,GETDATE()
END
GO

Explanation:
In above example we have created d2c_trgServerLogon trigger on all server for LOGON.
Whenever any new session will created d2c_trgServerLogon trigger will fire and mentioned query will execute.

top 15 sql server interview questions with answers

Q. What is sub query and its properties?
A. A sub-query is a query which can be nested inside a main query like Select, Update, Insert or Delete statements. This can be used when expression is allowed. Properties of sub query can be defined as

  • A sub query should not have order by clause.
  • A sub query should be placed in the right hand side of the comparison operator of the main query.
  • A sub query should be enclosed in parenthesis because it needs to be executed first before the main query.
  • More than one sub query can be included.

Q. What are the types of sub query?
A. There are three types of sub query –

  • Single row sub query which returns only one row.
  • Multiple row sub query which returns multiple rows.
  • Multiple column sub query which returns multiple columns to the main query. With that sub query result, Main query will be executed.

Q. What are the differences between local and global temporary tables?
A. Local temporary tables are visible when there is a connection, and are deleted when the connection is closed.

CREATE TABLE #<tablename>

Global temporary tables are visible to all users, and are deleted when the connection that created it is closed.

CREATE TABLE ##<tablename>

Q. What is COALESCE in SQL Server?
A. COALESCE is used to return first non-null expression within the arguments. This function is used to return a non-null from more than one column in the arguments. Lets suppose we have d2c_tblStudents table and having following data:

what-is-coalesce-in-sql-server

 

SELECT coalesce(studentName,studentClass,studentAddress) FROM d2c_tblStudents

output of above query will be “student1”. If we change above query as follow

SELECT coalesce(studentAddress,studentName,studentClass) FROM d2c_tblStudents

output will be remain same as previous one.

Q. What is a Trigger? How many types of triggers?
A. Triggers are used to execute a batch of SQL code when insert or update or delete commands are executed against a table. Triggers are automatically triggered or executed when the data is modified. It can be executed automatically on insert, delete and update operations.

There are four types of triggers and they are:
• Insert
• Delete
• Update
• Instead of

Q. What is an IDENTITY column in insert statements?
A. IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate key.

Q. What is the difference between UNION and UNION ALL?
A. UNION: To select related information from two tables UNION command is used. It is similar to JOIN command.
UNION All: The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It will not remove duplicate rows, instead it will retrieve all rows from all tables.

Q. What are the differences between Stored Procedure and the dynamic SQL?
A. Stored Procedure is a set of statements which is stored in a compiled form. Dynamic SQL is a set of statements that dynamically constructed at run time and it will not be stored in a Database and it simply execute during run time.

Q. What are Magic Tables in SQL Server?
A. Insert and Delete tables are created when the trigger is fired for any DML command. Those tables are called Magic Tables in SQL Server. These magic tables are used inside the triggers for data transaction.

Q. What is the difference between COMMIT and ROLLBACK?
A. Every statement between BEGIN and COMMIT becomes persistent to database when the COMMIT is executed. Every statement between BEGIN and ROLLBACK are reverted to the state when the ROLLBACK was executed.

Q. What is the difference between varchar and nvarchar types?
A. Varchar and nvarchar are same but the only difference is that nvarhcar can be used to store Unicode characters for multiple languages and it also takes more space when compared with varchar.

Q. What is SQL injection?
A. SQL injection is an attack by malicious users in which malicious code can be inserted into strings that can be passed to an instance of SQL server for parsing and execution. All statements have to checked for vulnerabilities as it executes all syntactically valid queries that it receives.
Even parameters can be manipulated by the skilled and experienced attackers

Q. What are the methods used to protect against SQL injection attack?
A. Following are the methods used to protect against SQL injection attack:

  • Use Parameters for Stored Procedures.
  • Filtering input parameters.
  • Use Parameter collection with Dynamic SQL.
  • In like clause, user escape characters.

Q. What is Filtered Index?
A. Filtered Index is used to filter some portion of rows in a table to improve query performance, index maintenance and reduces index storage costs. When the index is created with WHERE clause, then it is called Filtered Index.

Q. Explain the difference between DELETE , TRUNCATE and DROP commands?
A. Following are the differences

  • Once delete operation is performed, Commit and Rollback can be performed to retrieve data.
  • Once the truncate statement is executed, Commit and Rollback statement cannot be performed. Where condition can be used along with delete statement but it can’t be used with truncate statement.
  • Drop command is used to drop the table or keys like primary,foreign from a table.