遗留代码确实是这样:
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和返回值转换为布尔? 或者是其他东西?
UPDATE
它更改为这并没有纠正事项:
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;
}
...所以我不知道哪条路是优选的; 这似乎更直接给我...任何想法,任何人吗?