展示一個通用的 VBScript 函數 buildSQLInsert,根據表單提交欄位動態組裝 INSERT 陳述式,支援欄位類型推斷(文字/數值)、NULL 處理、欄位排除清單。
function buildSQLInsert(targetTable, omitFields)
iStr = "insert into " & targetTable & " "
vStr = "values ("
nStr = "("
for each x in request.form
fieldName = uCase(x)
if inStr(uCase(omitFields), x) = 0 then
fieldData = replace(request.form(fieldName), "'", "")
if trim(fieldData) = "" then
fieldData = "NULL"
vStr = vStr & fieldData & ", "
nStr = nStr & fieldName & ", "
else
typeDelimPos = inStr(fieldName, "_")
if typeDelimPos = 0 then
' 文字欄位
nStr = nStr & fieldName & ", "
vStr = vStr & "'" & fieldData & "', "
else
' 含類型前綴欄位,如 NUM_AGE
fieldType = left(fieldName, typeDelimPos - 1)
fieldName = mid(fieldName, typeDelimPos + 1)
nStr = nStr & fieldName & ", "
select case uCase(fieldType)
case "NUM"
vStr = vStr & fieldData & ", "
case else
vStr = vStr & "'" & fieldData & "', "
end select
end if
end if
end if
next
vStr = left(vStr, len(vStr) - 2) & ")"
nStr = left(nStr, len(nStr) - 2) & ") "
buildSQLInsert = iStr & nStr & vStr
end function
fName、lNameNUM_ 前綴,如 num_age → 對應欄位 age,不加引號"lname,fname"<form name=f method=post action="list4.asp">
First Name: <input type=text name="fName"><br>
Last Name: <input type=text name="lName"><br>
Age: <input type=text name="num_age"><br>
<input type="checkbox" value="Y" name="MyCheckBox"> Do you want this checked?<br>
<input type="submit" value="Submit">
</form>
response.write buildSQLInsert("", "") ' 全欄位
response.write buildSQLInsert("", "NUM_AGE") ' 排除 NUM_AGE
response.write buildSQLInsert("", "lname,fname") ' 排除 lname,fname
response.write buildSQLInsert("", "mycheckbox,fname") ' 排除 checkbox 與 fname
安全性提醒:此範例為教學示範,實際生產環境必須使用參數化查詢防止 SQL 注入,不可直接拼接使用者輸入。