[英]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'. 它在关键字“ 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: 谓词称为
EXISTS
,如果要测试的表/视图称为sys.tables
,则需要sys.tables
进行引用,最后需要将名称加引号,因此请尝试以下操作:
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. 如果该表存在,则将返回字符串值
TRUE
。
Also, you really shouldn't do concatenation for parameters, but rather use placeholders and parameters with the command object. 另外,您实际上不应该对参数进行串联,而应在命令对象中使用占位符和参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.