我有一个查询,基本上是这样说的:
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