tags:

views:

31

answers:

1

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results? For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?

Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
    Dim myCommand As SqlCommand
    Dim dr As SqlDataReader
    Dim mystring As String = String.Empty
    Try
        Dim myConn As New SqlConnection(ConnectionString)
        myConn.Open()
        myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
        dr = myCommand.ExecuteReader()
        While dr.Read()
                        mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
        End While
        dr.Close()
        myConn.Close()
    Catch e As Exception
        MessageBox.Show(e.Message)
    End Try
    Return mystring
End Function

Thanks.

A: 

The SQL Command should be

select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"

and you should change the display to show the count (Nbr in this example) to be something like:

mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf
MJB
Thanks MJB, I see - do the count as part of the sql statement rather than on the returned results. is the syntax correct for the statement? I'm getting "Column 'sysprocesses.hostname' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
madlan
I don't think it's possible to return more than one column when using Count?
madlan
SELECT loginame, hostname, COUNT(loginame) AS Nbr from sysprocesses where db_name(dbid) = '"
madlan
You are right -- I forgot to add in hostname on the group by.
MJB