遗留代码是这样做的:
public bool isValidField(string tableName, string fieldName)
{
bool retVal;
string tblQuery = string.Format("SELECT {0} FROM {1}", fieldName, tableName);
checkConnection();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
object objvalid = cmd.ExecuteScalar();
retVal = (null != objvalid);
}
catch
{
retVal = false;
}
return retVal;
}
...但我发现它并不总是有效。在调用该方法并获取之后false
,一些代码会更改表以添加一些列,但我得到:
列 ID 在规范中出现多次。
我在 StackOverflow 上发现了几个很有前途的 SQL 语句:
if exists(select * from sys.columns
where Name = N'columnName' and Object_ID = Object_ID(N'tableName'))
和
IF COL_LENGTH('table_name','column_name') IS NULL
...但我不确定如何在 C#/.NET 1.1 中实现它
我是否需要使用 ExecuteScalar 并将返回的值转换为布尔值?或者是其他东西?
更新
将其更改为此并不能解决问题:
public bool isValidField(string tableName, string columnName)
{
bool retVal;
string tblQuery = string.Format(
"COL_LENGTH({0},{1}) IS NULL",
tableName,
columnName);
checkConnection();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
object objvalid = cmd.ExecuteScalar();
retVal = Convert.ToBoolean(objvalid);
}
catch
{
retVal = false;
}
return retVal;
}
更新 2
奇怪的是,我在新代码中看到了更多错误消息。
更新 3
当我以这种方式更改代码时,它没有任何区别:
string tblQuery = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS"
+ " WHERE TABLE_NAME = @tableName AND COLUMN_NAME"
+ " = @columnName";
checkConnection();
try
{
SqlCeCommand cmd = objCon.CreateCommand();
cmd.CommandText = tblQuery;
SqlCeParameter tblNameParam = new SqlCeParameter(
"@tableName",
SqlDbType.NVarChar,
128);
tblNameParam.Value = tableName;
cmd.Parameters.Add(tblNameParam);
SqlCeParameter colNameParam = new SqlCeParameter(
"@columnName",
SqlDbType.NVarChar,
128);
colNameParam.Value = tableName;
cmd.Parameters.Add(colNameParam);
int i = (int)cmd.ExecuteScalar();
retVal = i > 0;
}
...所以我不知道哪种方式更可取;这对我来说似乎更直接......任何想法,有人吗?