这个查询:
string.Format("SELECT COUNT(*) FROM {0}", tableName);
...我将其用作“isValidTable(string tableName)”方法的核心,如果 tableName 不存在(特别是“指定的表不存在”),则会引发异常。
既然如此(它玩得不好,如果它不识别表名,它就会举手)让我想知道这段代码是否:
public bool isValidTable(string tableName)
{
bool validTable = false;
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
try
{
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandText = tblQuery;
object objcnt = cmd.ExecuteScalar();
if ((objcnt != null) && (objcnt != DBNull.Value))
{
validTable = Int32.Parse(objcnt.ToString()) > 0;
}
else
{
MessageBox.Show("NULL returned from isValidTable(). Remove this line."); //<- I never see this; if this is the case, an exception has been thrown
}
}
catch
{
return false;
}
return validTable;
}
...可以/应该简化为:
public bool isValidTable(string tableName)
{
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
try
{
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandText = tblQuery;
cmd.ExecuteScalar();
}
catch
{
return false;
}
return true;
}
?
更新
jp2code 认为:“在存在时选择案例((从 information_schema.tables 中选择 *,其中 table_name = '{0}'))然后 1 else 0 end”
是否有类似的代码来检查列是否存在?目前我的 isValidTable() 和 isValidColumn() 查询是相似的:
string tableQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
string columnQuery = string.Format("SELECT COUNT({0}) FROM {1}", columnName, tableName);
...但是如果我能够将其用于 isValidTable():
string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}')) then 1 else 0 end",
tableName);
...是否还有可用于检查有效列的扩展?就像是:
string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}' and column_name = '{1}')) then 1 else 0 end",
tableName, columnName);
???
更新 2
我意识到建议的 sql 比“我的方式”“更好”,但无论出于何种原因,当我使用“首选方法”时,所需的数据表不会被识别为存在(尽管它们确实存在) . 我正在使用的旧版软件不接受嵌套选择/子选择,或者......???
无论如何,评论讲述了这个故事:
string tblQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
// This is doubtless "more better," but when I use it, I get "No current work; no inventory file"
//string tblQuery = string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}')) then 1 else 0 end", tableName);