Click here to Skip to main content
15,910,411 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to check if the SQL table exists or not. If not exists, I will run create if exists, I will select some fields from that table.

What I have tried:

I wrote this for checking. But some error is coming that "Syantax error near tempoutlet"
below my code
bool exists;
            var chktb = new SqlCommand("select case when exists(select table_schema,table_name from information_schema.tables where schema_name='inventoryDB.mdf' and table_name='dbo.tempoutlet')", con);
            exists = (int)chktb.ExecuteScalar() == 1;

So any solution please
Posted
Updated 7-Dec-19 23:12pm
v3

Try this:
SQL
SELECT CASE WHEN OBJECT_ID('dbo.MyTable', 'U') IS NOT NULL THEN 1 ELSE 0 END
 
Share this answer
 
Comments
vijay_bale 10-Jun-17 3:42am    
Your solution worked.
Member 14682056 8-Dec-19 2:59am    
SELECT CASE WHEN OBJECT_ID('dbo.MyTable', 'U') IS NOT NULL THEN 1 ELSE 0 END.
What does 'U' refers to?
OriginalGriff 8-Dec-19 6:00am    
https://docs.microsoft.com/en-us/sql/t-sql/functions/object-id-transact-sql?view=sql-server-ver15
bagadurshah limbo 13-Dec-21 0:58am    
string tableCheck = "SELECT CASE WHEN OBJECT_ID('[MyAppDB].[User]', 'U') IS NOT NULL THEN 1 ELSE 0 END"; is this the correct format??
I know you already have a working solution, but just wanted to offer another. An alternate method would be to simply execute your select command in a try/catch. If the table doesn't exist, you can use the catch block to create the table. This avoids the overhead of a schema lookup every time.
 
Share this answer
 
SELECT CASE WHEN OBJECT_ID('dbo.MyTable', 'U') IS NOT NULL THEN 1 ELSE 0 END.
what does 'U' refers to?
 
Share this answer
 
Comments
CHill60 9-Dec-19 4:28am    
If you want to comment on, or ask a question about, a post then use the "Have a Question or Comment?" link next to it.
In this instance looking at the documentation is the better route OBJECT_ID (Transact-SQL) - SQL Server | Microsoft Docs[^] - it means that we are looking for the object id of a (User defined) table.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900