Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if table exists in SQL Server

I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.

When you Google for the answer, you get so many different answers. Is there an official/backward and forward compatible way of doing it?

Here are two possible ways of doing it. Which one among the two is the standard/best way of doing it?

First way:

IF EXISTS (SELECT 1             FROM INFORMATION_SCHEMA.TABLES             WHERE TABLE_TYPE='BASE TABLE'             AND TABLE_NAME='mytablename')     SELECT 1 AS res ELSE SELECT 0 AS res; 

Second way:

IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL     SELECT 1 AS res ELSE SELECT 0 AS res; 

MySQL provides the simple

SHOW TABLES LIKE '%tablename%';  

statement. I am looking for something similar.

like image 238
Vincent Avatar asked Oct 03 '08 16:10

Vincent


People also ask

How do you check if a table exist in SQL Server?

To check if a table exists in SQL Server, you can use the INFORMATION_SCHEMA. TABLES table. You can use this table with an IF THEN clause do determine how your query responds whether or not a table exists.

How do you check if a table exists or not?

To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.

How do you check if a table does not exist in SQL?

Using the OBJECT_ID and the IF ELSE statement to check whether a table exists or not. Alternative 2 : Using the INFORMATION_SCHEMA. TABLES and SQL EXISTS Operator to check whether a table exists or not.


2 Answers

For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version.

To check if a table exists use:

IF (EXISTS (SELECT *                   FROM INFORMATION_SCHEMA.TABLES                   WHERE TABLE_SCHEMA = 'TheSchema'                   AND  TABLE_NAME = 'TheTable')) BEGIN     --Do Stuff END 
like image 103
akmad Avatar answered Oct 14 '22 11:10

akmad


Also note that if for any reason you need to check for a temporary table you can do this:

if OBJECT_ID('tempdb..#test') is not null  --- temp table exists 
like image 27
James Bloomer Avatar answered Oct 14 '22 12:10

James Bloomer