首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP 經典 if 語句不執行:SUM 聚合查詢永遠返回記錄導致邏輯錯誤

     編輯:程式設計綜合問答

原代碼邏輯缺陷

set bgje = conn.execute("select sum(je) as num from xinxi where users='...' and yt like '辦公%'")
response.Write(not (bgje.bof and bgje.eof)) ' 永遠輸出 True
if not(bgje.bof and bgje.eof) then ...

根本原因

SUM()、COUNT() 等聚合函數永遠返回一行記錄(無匹配行時返回 NULL),因此 Recordset 永不為空,BOF/EOF 均為 False,導致 not(bof and eof) 恒為 True。

正確判斷邏輯

  1. 判斷主記錄集 rs(查詢 yonghu 表)是否存在:
    if rs.eof then ' 記錄不存在
        response.Write "用戶不存在"
    else
        ' 繼續處理
    end if
  2. 聚合查詢結果直接取值,無需判斷游標:
    bgje_num = bgje("num")
    if IsNull(bgje_num) then bgje_num = 0

修正後完整片段

exec = "select bl,ed from yonghu where users = '" & ur & "'"
set rs = server.createobject("adodb.recordset")
rs.open exec, conn, 3, 3

set zj = conn.execute("select sum(je) as num from xinxi where users='" & ur & "'")
set bgje = conn.execute("select sum(je) as num from xinxi where users='" & ur & "' and yt like '辦公%'")

if rs.eof then
    response.Write "記錄不存在"
else
    zj_num = zj("num")
    bgje_num = bgje("num")
    if IsNull(bgje_num) then bgje_num = 0

    if bgje_num = 0 then
        rs("bl") = 0
        rs("ed") = zj_num / 2
    else
        rs("bl") = bgje_num / zj_num * 100
        rs("ed") = zj_num / 2 - bgje_num
    end if
    rs.update
end if
rs.close

安全補充

拼接 SQL 存在注入風險,建議使用參數化命令(Command 對象 + Parameters 集合)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved