![](/img/trans.png)
[英]I need to check whether the data entered in form exists in database or not and if it exists redirect it to another page
[英]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.