繁体   English   中英

如何检查输入的表是否存在于数据库中?

[英]how to check whether the entered table exists in database?

我尝试使用此代码。

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

它在关键字“ SELECT”附近显示异常语法不正确。 关键字“表”附近的语法不正确。

帮我解决。

试试这个

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]

尝试这个..

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
        }

谓词称为EXISTS ,如果要测试的表/视图称为sys.tables ,则需要sys.tables进行引用,最后需要将名称加引号,因此请尝试以下操作:

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

您的查询也是不完整的,因为它表明您希望在条件成立的情况下执行某些操作,但是您从未声明要执行的操作。 有效的查询将使用以下形式:

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

如果该表存在,则将返回字符串值TRUE

另外,您实际上不应该对参数进行串联,而应在命令对象中使用占位符和参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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