This query:
string.Format("SELECT COUNT(*) FROM {0}", tableName);
...which I'm using as the guts of an "isValidTable(string tableName)" method, throws an exception if the tableName does not exist (specifically, "The specified table does not exist").
That being the case (it doesn't play nice, it throws up its hands if it doesn't recognize the table name) makes me wonder if this code:
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;
}
...could/should be simplified to:
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;
}
?
UPDATE
jp2code opined: "select case when exists((select * from information_schema.tables where table_name = '{0}')) then 1 else 0 end"
Is there similar code for checking if a column exists? Currently my isValidTable() and isValidColumn() queries are similar:
string tableQuery = string.Format("SELECT COUNT(*) FROM {0}", tableName);
string columnQuery = string.Format("SELECT COUNT({0}) FROM {1}", columnName, tableName);
...but if I were able to use this for isValidTable():
string.Format("select case when exists((select * from information_schema.tables where table_name = '{0}')) then 1 else 0 end",
tableName);
...is there also an extension of this that I could use for checking for valid columns? Something like:
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);
???
UPDATE 2
I realize that the suggested sql is "more better" than "my way," but for whatever reason, when I use "the preferred method," needed data tables are not recognized as existing (even though, of course, they do exist). Either the ancient version of software I'm using doesn't accept nested selects/sub-selects, or...???
At any rate, the comments tells the story:
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);