-- disable all constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
-- delete data in all tables
EXEC sp_MSForEachTable 'DELETE FROM ?'
-- enable all constraints
exec sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
Truncate Database/ Delete data from all tables of database
Labels: SQL , SQL Interview Questions , sqlserver
Taking a SQL Server Database Off-Line/ON-Line
Sometimes you will want to remove all access to a database for a period of time without detaching the database or deleting it. One option to achieve this is to take the database off-line. You can do this using standard SQL Server tools or Transact-SQL.
Using SQL Server Tools
The easiest way to take a SQL Server database off-line is using the graphical user interface tools provided. If you are using either SQL Server Management Studio or Enterprise Manager, you can simply right-click the name of a database. This causes a context-sensitive menu to appear. Within the "All Tasks" or "Tasks" submenu is the "Take Offline" option. Clicking this option takes the database off-line. You can return the database to an operational status by selecting "Bring Online" from the same menu.
ALTER DATABASE Command
The preferred manner in which to take a database off-line using Transact-SQL statements is with the ALTER DATABASE command. This command allows database administrators to modify database settings, files and filegroups.
Taking a Database Off-Line
The T-SQL for taking a database off-line is similar to that for setting restricted access mode. The simplest variation of the command is the following statement:
ALTER DATABASE database-name SET OFFLINE
The above command attempts to take the named database off-line immediately. If a user or a background process is currently connected to the database the command cannot be completed. In this situation, the ALTER DATABASE statement will be blocked and will wait until all connections are closed. This ensures that no transactions are rolled back unexpectedly. During the period of blocking, no new connections to the database will be permitted.
NB: Background processes that are running against SQL Server may cause the command to be indefinitely blocked, as can internal processes. The AUTO_UPDATE_STATISTICS_ASYNC in particular should be checked. If set to ON, the statement will be blocked.
Failing When Blocked
If you run the ALTER DATABASE command whilst users or processes may be connected, but you do not wish the command to be blocked, you can execute the statement with the NO_WAIT option. This causes the command to fail with an error.
ALTER DATABASE database-name SET OFFLINE WITH NO_WAIT
Forcing Disconnection of Users and Processes
In some cases it is appropriate to run the ALTER DATABASE command and allow it to be blocked until all of the current connections are closed. For SQL Servers that are used only internally to an organisation, each user can be contacted and asked to disconnect. Once they have, the command will complete automatically and the database will be inaccessible.
In other situations, for example a publicly accessible web site database, it may not be possible to ask users to disconnect. In these cases you may automatically disconnect users and to roll back their active transactions. This is achieved using the ROLLBACK clause.
The ROLLBACK clause can be used to immediately disconnect users or can be provided with a number of seconds to pause before taking the database off-line. To force the immediate disconnection of general users and processes and the rolling back of their transactions, use the following command:
ALTER DATABASE database-name SET OFFLINE WITH ROLLBACK IMMEDIATE
If desired, you can specify that there should be a pause before disconnecting the users. During this period any attempts to connect to the database are refused but existing connections are given a number of seconds to complete their processing. The following example statement pauses for two minutes before disconnecting users:
ALTER DATABASE database-name SET OFFLINE WITH ROLLBACK AFTER 120 SECONDS
Bringing a Database On-Line
Once you have completed any maintenance work and want to resume the use of the database, you can bring it back on-line using the ALTER DATABASE command:
ALTER DATABASE database-name SET ONLINE
Labels: SQL , SQL Interview Questions , sqlserver
Improve Query Performance using "With" Clause
Using with clause we can improve query performance.
Read complete Article
Labels: SQL , SQL Interview Questions
Improve Query Performance using "With" Clause
Using with clause we can improve query performance.
Read complete Article
Labels: SQL , SQL Interview Questions
What is use of "SET XACT_ABORT" in SQL
When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Depending upon the severity of the error, the entire transaction may be rolled back even when SET XACT_ABORT is OFF. OFF is the default setting.
Compile errors, such as syntax errors, are not affected by SET XACT_ABORT.
XACT_ABORT must be set ON for data modification statements in an implicit or explicit transaction against most OLE DB providers, including SQL Server. The only case where this option is not required is if the provider supports nested transactions.
example:
The following code example causes a foreign key violation error in a transaction that has other Transact-SQL statements. In the first set of statements, the error is generated, but the other statements execute successfully and the transaction is successfully committed. In the second set of statements, SET XACT_ABORT is set to ON. This causes the statement error to terminate the batch and the transaction is rolled back.
USE AdventureWorks;
GO
IF OBJECT_ID(N't2', N'U') IS NOT NULL
DROP TABLE t2;
GO
IF OBJECT_ID(N't1', N'U') IS NOT NULL
DROP TABLE t1;
GO
CREATE TABLE t1
(a INT NOT NULL PRIMARY KEY);
CREATE TABLE t2
(a INT NOT NULL REFERENCES t1(a));
GO
INSERT INTO t1 VALUES (1);
INSERT INTO t1 VALUES (3);
INSERT INTO t1 VALUES (4);
INSERT INTO t1 VALUES (6);
GO
SET XACT_ABORT OFF;
GO
BEGIN TRANSACTION;
INSERT INTO t2 VALUES (1);
INSERT INTO t2 VALUES (2); -- Foreign key error.
INSERT INTO t2 VALUES (3);
COMMIT TRANSACTION;
GO
SET XACT_ABORT ON;
GO
BEGIN TRANSACTION;
INSERT INTO t2 VALUES (4);
INSERT INTO t2 VALUES (5); -- Foreign key error.
INSERT INTO t2 VALUES (6);
COMMIT TRANSACTION;
GO
-- SELECT shows only keys 1 and 3 added.
-- Key 2 insert failed and was rolled back, but
-- XACT_ABORT was OFF and rest of transaction
-- succeeded.
-- Key 5 insert error with XACT_ABORT ON caused
-- all of the second transaction to roll back.
SELECT *
FROM t2;
GO
Labels: SQL , SQL Interview Questions
What is use of "SET XACT_ABORT" in SQL
When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Depending upon the severity of the error, the entire transaction may be rolled back even when SET XACT_ABORT is OFF. OFF is the default setting.
Compile errors, such as syntax errors, are not affected by SET XACT_ABORT.
XACT_ABORT must be set ON for data modification statements in an implicit or explicit transaction against most OLE DB providers, including SQL Server. The only case where this option is not required is if the provider supports nested transactions.
example:
The following code example causes a foreign key violation error in a transaction that has other Transact-SQL statements. In the first set of statements, the error is generated, but the other statements execute successfully and the transaction is successfully committed. In the second set of statements, SET XACT_ABORT is set to ON. This causes the statement error to terminate the batch and the transaction is rolled back.
USE AdventureWorks;
GO
IF OBJECT_ID(N't2', N'U') IS NOT NULL
DROP TABLE t2;
GO
IF OBJECT_ID(N't1', N'U') IS NOT NULL
DROP TABLE t1;
GO
CREATE TABLE t1
(a INT NOT NULL PRIMARY KEY);
CREATE TABLE t2
(a INT NOT NULL REFERENCES t1(a));
GO
INSERT INTO t1 VALUES (1);
INSERT INTO t1 VALUES (3);
INSERT INTO t1 VALUES (4);
INSERT INTO t1 VALUES (6);
GO
SET XACT_ABORT OFF;
GO
BEGIN TRANSACTION;
INSERT INTO t2 VALUES (1);
INSERT INTO t2 VALUES (2); -- Foreign key error.
INSERT INTO t2 VALUES (3);
COMMIT TRANSACTION;
GO
SET XACT_ABORT ON;
GO
BEGIN TRANSACTION;
INSERT INTO t2 VALUES (4);
INSERT INTO t2 VALUES (5); -- Foreign key error.
INSERT INTO t2 VALUES (6);
COMMIT TRANSACTION;
GO
-- SELECT shows only keys 1 and 3 added.
-- Key 2 insert failed and was rolled back, but
-- XACT_ABORT was OFF and rest of transaction
-- succeeded.
-- Key 5 insert error with XACT_ABORT ON caused
-- all of the second transaction to roll back.
SELECT *
FROM t2;
GO
Labels: SQL , SQL Interview Questions
Primary Key , Foreign Key Column Name for Key Constraint

Query written below will give you result as shown in image.
SELECT
[constraint_name] = f.[name],
[child_table] = OBJECT_NAME(f.parent_object_id),
[child_column] = cc.name,
[parent_table] = OBJECT_NAME(f.referenced_object_id),
[parent_column] = pc.name
FROM
sys.foreign_keys f
INNER JOIN
(
SELECT
c.[object_id],
c.name,
c.column_id,
ic.index_id
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON
c.[object_id] = ic.[object_id]
AND c.column_id = ic.column_id
) AS pc
ON
f.key_index_id = pc.index_id
INNER JOIN
sys.foreign_key_columns fkc
ON
f.[object_id] = fkc.constraint_object_id
AND pc.[object_id] = fkc.referenced_object_id
AND fkc.referenced_column_id = pc.column_id
INNER JOIN
sys.columns cc
ON
fkc.parent_object_id = cc.[object_id]
AND fkc.parent_column_id = cc.column_id
ORDER BY
constraint_name,
child_table
Labels: SQL
Primary Key , Foreign Key Column Name for Key Constraint

Query written below will give you result as shown in image.
SELECT
[constraint_name] = f.[name],
[child_table] = OBJECT_NAME(f.parent_object_id),
[child_column] = cc.name,
[parent_table] = OBJECT_NAME(f.referenced_object_id),
[parent_column] = pc.name
FROM
sys.foreign_keys f
INNER JOIN
(
SELECT
c.[object_id],
c.name,
c.column_id,
ic.index_id
FROM
sys.columns c
INNER JOIN
sys.index_columns ic
ON
c.[object_id] = ic.[object_id]
AND c.column_id = ic.column_id
) AS pc
ON
f.key_index_id = pc.index_id
INNER JOIN
sys.foreign_key_columns fkc
ON
f.[object_id] = fkc.constraint_object_id
AND pc.[object_id] = fkc.referenced_object_id
AND fkc.referenced_column_id = pc.column_id
INNER JOIN
sys.columns cc
ON
fkc.parent_object_id = cc.[object_id]
AND fkc.parent_column_id = cc.column_id
ORDER BY
constraint_name,
child_table
Labels: SQL
What is the DEADLOCK ?
A deadlock is a situation in which two transactions conflict with each other and the only resolution is to cancel one transaction.
Labels: SQL , SQL Interview Questions , sqlserver
How to find out column names and their datatypes in a given table using a query in SQL Server?
Using the table tablename, write the query as follows -
Select * from information_schema.columns where table_name = tablename
Labels: SQL , SQL Interview Questions , sqlserver
What is the DEADLOCK ?
A deadlock is a situation in which two transactions conflict with each other and the only resolution is to cancel one transaction.
Labels: SQL , SQL Interview Questions , sqlserver
How to find out column names and their datatypes in a given table using a query in SQL Server?
Using the table tablename, write the query as follows -
Select * from information_schema.columns where table_name = tablename
Labels: SQL , SQL Interview Questions , sqlserver
What is the EXISTS operator in SQL Server ? OR What is the EXISTS keyword in SQL Server ?
When you use EXISTS, you do not really returned data - instead you return a simple TRUE/FALSE regarding the existence of data that meets the criteria established in the query that the EXISTS statement is operated against.
EXISTS simply test whether the inner query returns any row. If it does, then the outer query proceeds, if not, the outer query does not executes, and the entire SQL statement returns nothing.
The EXISTS condition is considered "to be met " if the subquery returns at least one row.
The syntax for EXISTS condition is -
SELECT columns FROM sometable WHERE EXISTS (subquery)
Labels: SQL , SQL Interview Questions , sqlserver
What is a Subquery ?
A Subquery is a normal T-SQL query that is nested inside another query. They are created using parentheses when you have a SELECT statement that serve as the basis for the either part of the data or the condition in another query.
Subqueries are generally used to fill one of couple of needs -
1. Break a query up into a series of a logical steps.
2. Provide a listing to be the target of a WHERE clause together with [IN|ESISTS|ANY|ALL].
3. TO provide a lookup driven by each individual record in a parent query.
Eg.
SELECT SelectList FROM SomeTable WHERE SomeColumn = (SELECT SingleColumn FROM SomeTable WHERE Condition that results in only one row returned)
Labels: SQL , SQL Interview Questions , sqlserver
What is the EXISTS operator in SQL Server ? OR What is the EXISTS keyword in SQL Server ?
When you use EXISTS, you do not really returned data - instead you return a simple TRUE/FALSE regarding the existence of data that meets the criteria established in the query that the EXISTS statement is operated against.
EXISTS simply test whether the inner query returns any row. If it does, then the outer query proceeds, if not, the outer query does not executes, and the entire SQL statement returns nothing.
The EXISTS condition is considered "to be met " if the subquery returns at least one row.
The syntax for EXISTS condition is -
SELECT columns FROM sometable WHERE EXISTS (subquery)
Labels: SQL , SQL Interview Questions , sqlserver
What is a Subquery ?
A Subquery is a normal T-SQL query that is nested inside another query. They are created using parentheses when you have a SELECT statement that serve as the basis for the either part of the data or the condition in another query.
Subqueries are generally used to fill one of couple of needs -
1. Break a query up into a series of a logical steps.
2. Provide a listing to be the target of a WHERE clause together with [IN|ESISTS|ANY|ALL].
3. TO provide a lookup driven by each individual record in a parent query.
Eg.
SELECT SelectList FROM SomeTable WHERE SomeColumn = (SELECT SingleColumn FROM SomeTable WHERE Condition that results in only one row returned)
Labels: SQL , SQL Interview Questions , sqlserver
How to find nth highest salary from Employee table in SQL Server?
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP n salary FROM employee ORDER BY salary DESC) a ORDER BY salary
Labels: SQL , SQL Interview Questions , sqlserver
How to find nth highest salary from Employee table in SQL Server?
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP n salary FROM employee ORDER BY salary DESC) a ORDER BY salary
Labels: SQL , SQL Interview Questions , sqlserver
What is the IDENTITY property in SQL Server?
The IDENTITY property enables you to use system generated values in your tables column. It is similar to the auto number datatype in MS ACCESS. You are allowed a single column in each table with the IDENTITY property. Typically, IDENTITY column generates system assigned keys. To enforce entity integrity, you must uniquely identify each row in a table. If no natural column or set of column does this, you might went to create an IDENTITY column.
You can use the IDENTITY property if the column to which it is being assigned is an integer or compatible with an integer. Therefore you can use the following datatypes - tinyint, bigint, smallint, numeric, integer, decimal.
You can use numeric and decimal only if they have scale of 0 (zero). It must also not allowed to NULL.
Labels: SQL , SQL Interview Questions , sqlserver
How to convert timestamp data to date data (datetime datatype) in SQL Server?
The name timestamp is a little misleading. Timestamp data has nothing to do with dates and times and can not be converted to date data. A timestamp is a unique number within the database and is equivalent to a binary(8)/varbinary(8) datatype. A table can have only one timestamp column. Timestamp value of a row changes with every update of the row. To avoid the confusion, SQL Server 2000 introduced a synonym to timestamp, called rowversion.
Labels: SQL , SQL Interview Questions , sqlserver