Click here to Skip to main content
15,889,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Guys,

I have a select subqueries which getting count from multi table. I define every total as something name. How do I get every column name and its value? Do I have to manual specify every name from the count?

C#
Private Function ShowTotalCount()
    Dim rdr As SqlDataReader
    Dim cmd As SqlCommand = Nothing
    Dim totcount As Integer = 0
    Dim CommandText As String = "SELECT
    (SELECT COUNT(*) FROM [dbo].[MyDownTime]) as count_mydowntime,
    (SELECT COUNT(*) FROM [dbo].[MyDownTime]) as count_mydowntime,
    (SELECT COUNT(*) FROM [dbo].[MyOutput]) as count_myoutput,
    (SELECT COUNT(*) FROM [dbo].[MySpeed]) as count_myspeed,
    (SELECT COUNT(*) FROM [dbo].[MyTemperature]) as count_mytemperature,
    (SELECT COUNT(*) FROM [dbo].[MyUtility]) as count_myutility"
        objlocalconn.Open()
        cmd = New SqlCommand(CommandText, objlocalconn)
        cmd.CommandType = CommandType.Text
        rdr = cmd.ExecuteReader()
        If rdr.HasRows Then
            Do While rdr.Read()
                Console.WriteLine("{0} - {1}", rdr["count_mydowntime"], Convert.ToInt32(rdr.GetValue(0)))
    Loop
        End If
End Function


I found mostly just pass the value as from single number returned. But how about if the queries have "AS" like
XML
(select count(*) AS viewthis1),select count(*) AS viewthis2)
where I want to it read in SQLDataReader of viewthis1 and viewthis2
Posted
Updated 15-Aug-16 0:29am
v2

1 solution

Try this inside your While loop to iterate over each column of each row regardless of the column name. If you need to access only certain columns, provide the column name instead of its index:

VB
For i = 0 To rdr.FieldCount - 1
    Console.WriteLine(rdr.GetName(i), dr(i)))
Next
 
Share this answer
 
v2
Comments
Maciej Los 15-Aug-16 6:32am    
5ed!

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