Wednesday, April 25, 2012

Determine whether a table is exist or not in Sql Server database

In this post I am going to explain about “How to check whether a table is exist or not in Sql Server database”. In many situations we might need to identify whether a table is exist or not in a sql server database. This is very simple .
To Do this create one table with the following script :

USE Practice
GO
CREATE TABLE Test
(ID INT,
COL VARCHAR(100))
GO
INSERT INTO Test
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
GO

Now we have created a table with two rows and the Table name is “Test”. To check whether table is created or not or table is existed or not uses the following query:

Use Practice
IF EXISTS (SELECT 1
          FROM INFORMATION_SCHEMA.TABLES
          WHERE TABLE_TYPE='BASE TABLE'
          AND TABLE_NAME='Test')
              SELECT 'table exists.'
      ELSE
              SELECT 'table does not exist.'

Output: table exists.

Now drop the Table “Test “ using the following drop statement.


Use Practice Drop table Test



Now the Table test is deleted and use the same Query to test the Table exist or not .Then you will get the output is 'table does not exist.

Output : table does not exist.




No comments:

Post a Comment