Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I would like to add up every row in a column.

I know I am missing a integer changing thing on dr(i).

If there are easier methods please let me know.

VB
Sub Add()
        cmdStr = "SELECT [col3] FROM [table1];"
        End Select
        i = 0
        connStr = "server=myServer;initial catalog=myDB;uid=myID;pwd=myPassword"
        Using conn As New SqlConnection(connStr)
            conn.Open()
            Using cmd As New SqlCommand(cmdStr, conn)
                Using dr As SqlDataReader = cmd.ExecuteReader()
                    While dr.Read()
                        count = count + dr(i)
                        i = i + 1
                    End While
                End Using
            End Using
        End Using
        TextBox2.Text = count
End Sub
Posted
Updated 1-Jun-13 7:42am
v2
Comments
CHill60 1-Jun-13 14:05pm    
Why not just do this in the Sql in cmdStr??
[no name] 1-Jun-13 14:09pm    
Agreed. You can easily just select the Sum from the database and be done with it.
teledexterus 1-Jun-13 14:27pm    
How do you select sum from the database?
And what is the syntax of the integer form of dr(i)?

1 solution

1) To select sum from the database use something like..
VB
cmdStr = "SELECT SUM(col3) FROM table1"


2) For getting integers from sqldatareader use dr.GetInt...
sqldatareader example from dotnetperls[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900