0

我有一个查询,基本上是这样说的:

SELECT DISTINCT [DB_ID]
FROM [TableX]
WHERE ([ForeignKey]=@ForeignKey);

一旦我有了这个,我返回第一个 DB_ID(应该只有一个)。

我为调用它而编写的例程是用 C# 编写的,因此无论 DB_ID 的名称是什么,我都可以获得任何表名的数据库 ID。

大多数 ForeignKey 参数是整数,但有些是字符串值。然后,要添加参数值,我使用

Parameter.AddWithValue(ForeignKeyName, objValue);

这个例程与现有的数据库 ID 配合得非常好;但是,当找不到 ForeignKey 时,它会返回 3 而不是 null。

我意识到我可以使用蛮力技术并简单地编写两种样式的 SQL 语句(一种接受整数,另一种接受字符串)并完全避免参数,但我想知道并理解为什么这个参数化例程不是在职的。

有人可以向我解释为什么这不起作用吗?

/// <summary>
/// Locates the Primary Key Value for a Table using the Table's Foreign Key
/// </summary>
/// <param name="tableName">Name of the Table to Delete from</param>
/// <param name="primaryKey">Name of the Primary Key in the Table</param>
/// <param name="foreignKey">Name of the Foreign Key in the Table</param>
/// <param name="id">Foreign Key Value to Search for in the Table</param>
/// <returns>Primary Key Database ID for this Table Record</returns>
List<int> tableSelectId(string tableName, string primaryKey, string foreignKey, object id) {
  string sqlText = string.Format("SELECT DISTINCT [{0}] " +
    "FROM [{1}] WHERE ([{2}]=@id);", primaryKey, tableName, foreignKey);
  DataTable table = new DataTable("IDs");
  OleDbDataAdapter da = new OleDbDataAdapter(sqlText, AccessConnection);
  da.SelectCommand.Parameters.AddWithValue("@id", id);
  try {
    da.Fill(table);
  } catch (OleDbException err) {
    clsLogger.LogException((Exception)err);
  }
  List<int> vals = new List<int>(table.Rows.Count);
  foreach (DataRow row in table.Rows) {
    vals.Add((int)row[0]);
  }
  return vals;
}

eof

4

1 回答 1

1

重温这一点:原来另一位开发人员正在从事同一个项目,他复制了一个不同的数据库来工作,该数据库有一个空表。

该表前一小时有记录,下一小时则没有!

简而言之,上面的代码片段有效。

于 2009-09-11T15:39:50.023 回答