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.
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.
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 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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With