1

i need to count the distinct row in sql database and after that the result will be stored in Int variable

for example count the distinct row(SalesID) in tblSales(table) and store it in NUM(int variable) .

TIA :)

    Public Function ExecuteQuery(ByVal query As String) As DataTable
        Try
           Dim cn As New SqlConnection(con)
           Dim da As New SqlDataAdapter(query, cn)
           Dim cb As New SqlCommandBuilder(da)
           Dim dt As New DataTable
           da.Fill(dt)

           Return dt
        Catch ex As Exception
           MessageBox.Show(ex.Message)
           Return Nothing
        End Try
    End Function

    Private Sub btnFinish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFinish.Click 
       dim count as string = "select distinct count(SalesID) from tblSales"  
       ExecuteQuery(count) 
       dim Num as Integer = Int32.Parse(Val(count)) 
    End Sub
4
  • Have you tried anything? Please provide what you have tried. Commented Oct 30, 2013 at 6:38
  • i tried this one Private Sub btnFinish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFinish.Click dim count as string = "select distinct count(SalesID) from tblSales" ExecuteQuery(count) dim Num as Integer = Int32.Parse(Val(count)) End Sub Commented Oct 30, 2013 at 6:47
  • Public Function ExecuteQuery(ByVal query As String) As DataTable Try Dim cn As New SqlConnection(con) Dim da As New SqlDataAdapter(query, cn) Dim cb As New SqlCommandBuilder(da) Dim dt As New DataTable da.Fill(dt) Return dt Catch ex As Exception MessageBox.Show(ex.Message) Return Nothing End Try End Function Commented Oct 30, 2013 at 6:47
  • edit your question and add what you've tried there. Commented Oct 30, 2013 at 6:48

1 Answer 1

3

you could try something like this

Dim num As Integer
Dim sql As String
sql = "select count(distinct SalesID) from tblSales"
Using con As New SqlConnection(connStr)
    Using com As New SqlCommand(sql, con)
        con.Open()
        num = Convert.ToInt32(com.ExecuteScalar())
    End Using
End Using
Sign up to request clarification or add additional context in comments.

1 Comment

@PaoloHerreraBabas. Its Correct then tick it. Because it use for future reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.