Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : check if table exists, otherwise create it

Tags:

sql-server

I have this code I am converting from MySQL:

IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND TABLE_NAME = 'odds_soccer') 
    CREATE TABLE "odds_soccer" (...)

Only problem is... If I try run it twice, it will stump second time with error

Msg 2714, Level 16, State 6, Line 1
There is already an object named 'odds_soccer' in the database.

Since I actually found my solution at SO, I am not sure why the code is not working.

I am currently running it as a query from Microsoft SQL Server Management Studio having selected my database.

like image 340
Tom Avatar asked Mar 02 '17 15:03

Tom


People also ask

How can you tell if a table is created or not 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.

How do you check if a table already exists in SQL Server?

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 exists in a schema?

How to check whether a table (or view) exists, and the current user has access to it? SELECT EXISTS ( SELECT FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' ); The information schema is mainly useful to stay portable across major versions and across different RDBMS.


1 Answers

For creating table

IF NOT EXISTS (SELECT 'X'
                   FROM   INFORMATION_SCHEMA.TABLES
                   WHERE  TABLE_NAME = 'table_name'
                          AND TABLE_SCHEMA = 'schema')
BEGIN
    create..
END

For dropping existing table create new table

IF Object_id('TEMPDB.schema_name.table', 'U') IS NOT NULL
    DROP TABLE table;
like image 171
Chanukya Avatar answered Oct 27 '22 01:10

Chanukya