2009-08-26 46 views
0

我有一個查詢,基本上這樣說:的Microsoft Access參數查詢失敗偶爾

SELECT DISTINCT [DB_ID] 
FROM [TableX] 
WHERE ([ForeignKey][email protected]); 

一旦我有這個,我回到第一DB_ID(應該只有一個)。

我編寫的用於調用此函數的例程是在C#中,以便我可以獲取任何表名的數據庫ID,而不管DB_ID的名稱是什麼。

大部分的ForeignKey參數都是整數,但有些是字符串值。要添加參數值,我使用

Parameter.AddWithValue(ForeignKeyName, objValue); 

這個例程對於現有的數據庫ID很棒,但是,如果找不到ForeignKey,則返回3而不是null。我知道我可以使用蠻力技術,並且簡單地寫兩種樣式的SQL語句(一個接受Integer,另一個接受String)並完全避免參數,但我想知道並理解爲什麼會這樣參數化例程不起作用。

難道有人請向我解釋爲什麼這不起作用?

/// <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}][email protected]);", 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

回答

1

重溫這樣的:原來,另一個開發人員正在研究同一個項目,他複製了在不同的數據庫上下工夫其中有一個空表。

表格有一個小時有記錄,下一小時它沒有!

總之,上面的代碼片段工作。