具有嵌套循环的动态TSQL查询

时间:2019-03-11 17:42:01

标签: sql sql-server vbscript adodb

我已经使用SQL Server作为后端构建了基于Intranet的测验systm。测验分数存储在单独的表中,每个测验一个。根据职位的不同,员工只能访问部分或全部测验。 我试图确定最佳的方式来运行一个查询,该查询将总计或汇总每个人已完成的测验的数量,并将其与分配给他们的预定测验的数量进行比较。一旦两个数字匹配,它们就被认为是完整的,我可以将最终结果导出到另一个数据库。

我尝试使用VBS循环遍历测验表并检查每个人的分数,但是我似乎无法使其正常工作,因为它有点依赖于遍历每个员工记录,然后不得不循环再次通过分配给每个表的所有表名。我最终循环了初始查询而不是次级查询,以获取计数:

Set rs = CreateObject("ADODB.Recordset")
rs.CursorLocation = 3

rs.Open "Select v.emp_num, v.position, p.group_id From ValidApplicants as v, Positions as p Where v.complete = 0 and v.notified = 0 And v.position = p.Position", conn
RSCount = rs.RecordCount

i = 0
Do until i = RSCount
    strempNum = rs("emp_num")
    strPosition = rs("position")
    strGroupID = rs("group_id")

    Set rs2 = CreateObject("ADODB.Recordset")
    rs2.CursorLocation = 3

    rs2.Open "Select quiz_name, tblname, quiz_code From quizfilter Where group_id in (1, "& strGroupID &")",conn
    recCount = rs2.RecordCount

    x = 0
    Do until x = recCount
        strQuizName = rs2("quiz_name")
        strTable = rs2("tblname")
        strCode = rs2("quiz_code")

        Set rez = CreateObject("ADODB.Recordset")
        rez.CursorLocation = 3

        j = 0
        Do until j = recCount
            rez.Open "SELECT (SELECT COUNT(*) FROM "& strTable &" WHERE 
            pass_fail = 1 And employee_num = 7275) AS SumCount"
            j = j + 1
        Loop

        Set rez2 = CreateObject("ADODB.Recordset")
        rez2.CursorLocation = 3
        rez2.Open "Select quiz_count From QuizGroups Where group_id = "& strGroupID &"",conn
        if not (rez2.eof) then
            strQuizCount = rez2("quiz_count")
        end if

        rs2.MoveNext
        x = x + 1
    Loop

    if not users_eof then
        for record=0 to UBound(dataArray,2)
            strtheCount = dataArray(user_score,record)
        Next

        if (strtheCount = strQuizCount) then
            Wscript.Echo "Count is "& strQuizCount &""
        end if
    end if

    rs2.close
    set rs2 = nothing

    rs.MoveNext
    i = i + 1
Loop

如果有人可以指出正确的方向,也许有办法通过SQL存储过程中的动态查询来实现这一目标?

非常感谢

0 个答案:

没有答案