user3377879
user3377879

Reputation: 43

how to check whether the entered table exists in database?

I tried with this code..

string tabExist = "IF EXIST ( SELECT [name] FROM sys.table WHERE [name]=" + combCustomerName.Text + "" + ")";
        SqlCommand tabExistCmd = new SqlCommand(tabExist, con);
        tabExistCmd.ExecuteNonQuery();

It is showing exception Incorrect syntax near the keyword 'SELECT'. Incorrect syntax near the keyword 'table'.

Help me out to resolve it.

Upvotes: 0

Views: 118

Answers (5)

jpw
jpw

Reputation: 44911

The predicate is called EXISTS and the table/view you test against if called sys.tables and finally the name needs to be quoted so try this:

string tabExist = "IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = '" + combCustomerName.Text + "')";

Your query is also incomplete, as it states that you want to do something if the condition holds true, but you never state what to do. A valid query would use this form:

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name]='Orders') SELECT 'TRUE' AS Status

This would return the string value TRUEif the table exists.

Also, you really shouldn't do concatenation for parameters, but rather use placeholders and parameters with the command object.

Upvotes: 0

Revan
Revan

Reputation: 1144

Try this..

string tabExist = "IF EXIST ( SELECT count(*) FROM sys.Tables WHERE TABLE_NAME =" + combCustomerName.Text +")";
        SqlCommand tabExistCmd = new SqlCommand(tabExist, con);
        if((int)tabExistCmd.ExecuteScalar()>0)
        {
          //Table Exist
        }
        else
        {
          //Table does not exist
        }

Upvotes: 1

Sujith H S
Sujith H S

Reputation: 477

Try with this

string tabExist = "IF EXIST ( SELECT * FROM sys.Tables WHERE TABLE_NAME =" + combCustomerName.Text +")";
    SqlCommand tabExistCmd = new SqlCommand(tabExist, con);
    tabExistCmd.ExecuteNonQuery();

Upvotes: 1

tuespetre
tuespetre

Reputation: 1887

You want to use this:

IF OBJECT_ID(N'tablenamehere') IS NOT NULL [whatever else you want to do here]

Upvotes: 0

Tigran
Tigran

Reputation: 62265

You probably need just write name, and also use parameters in your query and not plaint text concatenation.

Upvotes: 0

Related Questions