在 ASP 中動態構建 SQL 語句時,表名作為變量拼接最容易忽略關鍵字前的空格,導致語法錯誤。本文通過實例演示正確的字符串拼接技巧。
Dim km
km = "東方不敗"
strSql = "Update " & km & "Set Sfhwhy='Y' where name='" & hy & "'"
' 生成 SQL: Update 東方不敗Set Sfhwhy='Y' where name='...' ← 缺少空格!
"Update 東方不敗 Set..." 卻正常
strSql = "Update " & km & " Set Sfhwhy='Y' where name='" & hy & "'"
' 關鍵:km 後、Set 前必須有空格
' 表名無法參數化,但值必須參數化
strSql = "Update [" & km & "] Set Sfhwhy=@p1 where name=@p2"
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = strSql
cmd.Parameters.Append cmd.CreateParameter("@p1", adVarChar, adParamInput, 1, "Y")
cmd.Parameters.Append cmd.CreateParameter("@p2", adVarChar, adParamInput, 50, hy)
cmd.Execute
注意:Access 表名含中文/空格需用 [] 括起。
Response.Write strSql
Response.End
' 瀏覽器顯示生成的完整 SQL,肉眼檢查空格、引號、關鍵字
動態拼接 SQL 時,關鍵字之間必須有空格。養成 Response.Write strSql 調試習慣,90% 的語法錯誤立現。值類參數務必使用參數化查詢防注入,表名/列名無法參數化時嚴格驗證白名單。