0

基本的に、次のようなクエリがあります。

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

これを取得したら、最初の DB_ID を返します (1 つしかないはずです)。

これを呼び出すために作成したルーチンは C# で記述されているため、DB_ID の名前に関係なく、任意のテーブル名のデータベース ID を取得できます。

ほとんどの ForeignKey パラメータは整数ですが、一部は文字列値です。パラメータ値を追加するには、次を使用します

Parameter.AddWithValue(ForeignKeyName, objValue);

このルーチンは、既存のデータベース ID でうまく機能します。ただし、ForeignKey が見つからない場合は、null の代わりに 3 を返します。

ブルート フォース手法を使用して、単純に 2 つのスタイルの 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

これを再検討する: 別の開発者が同じプロジェクトに取り組んでいて、空のテーブルを持つ別のデータベースにコピーして作業していたことが判明しました。

1 時間はテーブルにレコードがあり、次の 1 時間はレコードがありませんでした!

つまり、上記のコード スニペットは機能します。

于 2009-09-11T15:39:50.023 に答える