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.
Here in the above code, the table name is
Mapping_APCToFANavigator
.consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. To do this open visual studio and do the following:
Right click on t1, then Script table as, then DROP and Create To, then New Query Editor
you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one.
Thanks
I know it is an old question but I have found this possibility if you plan to call it often.
Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it.
Just adding here, for the benefit of developers and fellow DBAs
a script that receives @Tablename as a parameter
(which may or may not contain the schemaname) and returns the info below if the schema.table exists:
I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.
It raises an error when either you passed an empty string, wrong schema name or wrong table name.
this could be inside a procedure and return -1 for example.
As an example, I have a table called "Facts.FactBackOrder" in one of my Data Warehouse databases.
This is how I achieved this: