在SQL查询中使用SqlDataReader的结果

时间:2013-04-18 14:31:22

标签: sql sql-server vb.net

我想让我的读者的结果能够在另一个SQL命令的WHERE子句中使用。我试图将读者放入一个变量中使用,但它不起作用。我之前从未使用过读者,所以我不知道它们是如何工作的。任何人都可以让我知道如何让读者的结果进入哪里声明?感谢。

代码:

        Dim courseSelectCom = New SqlCommand("select stuff((select ','+course_name from course where school= '" & schoolSelect & "' for xml path ('')),  1, 1, '')", connection)

        Dim reader = courseSelectCom.ExecuteReader()
        If reader.Read() Then
            Dim courseVar As String
            courseVar = "%" & reader("course_name") & "%"

            Using totalStudentCom = New SqlCommand("SELECT COUNT(student_ID) FROM student " & "course_name like @course", connection)
                totalStudentCom.Parameters.AddWithValue("@course", courseVar)
                Dim result = totalStudentCom.ExecuteScalar()
                 MessageBox.Show("Students for course = " & result.ToString)
            End Using
        End If

1 个答案:

答案 0 :(得分:1)

这里有几个问题 首先你应该使用参数化查询而不是字符串连接来构建sql命令
打开DataReader时,除非您在连接字符串中指定了子串MultipleActiveResultSets=True;,否则连接对象无法提供其他命令

Dim courseSelectCom = New SqlCommand("select course_name from course where school= @school", connection)
courseSelectCom.Parameters.AddWithValue("@school", schoolSelect)
Dim reader = courseSelectCom.ExecuteReader()
if reader.Read() then
    Dim courseVar As String
    courseVar = "%" & reader("course_name") & "%"

    Using totalStudentCom = new SqlCommand("SELECT COUNT(student_ID) FROM student " & _
                                "course_name like @course", connection)
        totalStudentCom.Parameters.AddWithValue("@course", courseVar)
        Dim result = totalStudentCom.ExecuteScalar()
        MessageBox.Show("Students for course = " & result.ToString)
    End Using
End If

请记住,这仅适用于MARS is enabled