0

我想让我的读者的结果能够WHERE在另一个 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
4

1 回答 1

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时才有效

于 2013-04-18T14:37:55.010 回答