将Count(Record)结果转换为VB.Net中的变量

时间:2016-03-29 06:30:55

标签: sql-server vb.net

我想将记录计数捕获到变量但代码不起作用。请协助

Dim PrevRgAPAC As Integer
   Dim con As New SqlConnection
   Dim cmd As New SqlCommand
   Dim rd As SqlDataReader

 con.ConnectionString = "Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true"
        cmd.Connection = con
        con.Open()

        cmd.CommandText = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"

        rd = cmd.ExecuteReader
        If rd.HasRows Then
            rd.Read()
            PrevRgAPAC = rd.Item("exec")

        Else
            MsgBox("Not Found")
        End If

谢谢

1 个答案:

答案 0 :(得分:0)

尝试使用SqlCommand.ExecuteScalar Method

PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())

假设PrevRgAPAC是要存储count值的变量。所以你的代码看起来像这样:

Dim PrevRgAPAC As Int32 = 0
Dim sql As String = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"

Using conn As New SqlConnection("Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true")
    Dim cmd As New SqlCommand(sql, conn)
    Try
        conn.Open()
        PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
End Using