I tried your code and I do not see where you are having an issue, unless your Session.Item("UserId") is not being set properly. I do not have a session so I improvised in a console application. I am trying to figure out what exactly you are trying to do because the Count(Distinct(UserId)) will always return 1. Since you are asking for a specific userId, then asking to distinct it and then count it. so 1 user returns 100 times, distinct give you the only user in the list, so 1 returns.
Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Using connection = New SqlConnection(ConnectionString)
Using command As New SqlCommand()
Dim userId As String = "3"
command.Connection = connection
command.CommandText = "Select Count(Distinct(UserId)) FROM tblTable _
where UserId= '" & userId & "'"
connection.Open()
Dim result = command.ExecuteScalar()
Console.WriteLine(result)
connection.Close()
End Using
End Using
If you are just looking to see if the user exists, try the following code.
Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Using connection = New SqlConnection(ConnectionString)
Using command As New SqlCommand()
Dim userId As String = "3"
command.Connection = connection
command.CommandText = "Select Count(UserId) FROM tblTable _
where UserId= '" & userId & "'"
connection.Open()
Dim result = command.ExecuteScalar()
Console.WriteLine(result)
connection.Close()
End Using
End Using
This will tell you in the how many rows containing the userIds are in the table
if you want to see the UserID/Site Comination with counts that is a another story
Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
Using connection = New SqlConnection(ConnectionString)
Using command As New SqlCommand()
Dim userId As String = "3"
command.Connection = connection
command.CommandText = "Select UserID, Count(SiteId) FROM tblTable where _
UserId= '" & userId & "'" & " Group By UserId"
connection.Open()
Dim dataReader = command.ExecuteReader()
Do While dataReader.Read()
Console.WriteLine( _
vbTab & "UserId: {0}" & vbTab & "SiteID Count: {1}", _
dataReader(0), dataReader(1))
Loop
connection.Close()
End Using
End Using
I think that should get you on the correct Track