在 ADO 建構動態 SQL 字串時,直接串接乘號 * 會導致語法錯誤,因為 * 在 SQL 中為萬用字元(SELECT *),解析器誤判。
-- 錯誤:字串串接時 * 被視為 SQL 關鍵字 string sql = "SELECT TOP " + (pageIndex-1)*pageSize + " E_Id FROM Emp ORDER BY E_Id ASC";
int count = (this.AspNetPager1.CurrentPageIndex - 1) * this.AspNetPager1.PageSize; string sql = "SELECT TOP " + count + " E_Id FROM Emp ORDER BY E_Id ASC";
int count = (pageIndex - 1) * pageSize;
string sql = "SELECT TOP @TopCount E_Id FROM Emp ORDER BY E_Id ASC";
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@TopCount", count);
// 執行查詢
}
參數化查詢同時解決:運算符衝突、SQL 注入風險、計畫重用問題,為企業級開發標準做法。