简体   繁体   中英

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.

Try with this

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

您可能只需要写name ,并在查询中使用参数 ,而不要使用纯文本串联。

您要使用此:

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

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
        }

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 TRUE if the table exists.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM