I have the following code:

Imports System.Data.SqlClient
Public Class Main
    Protected WithEvents DataGridView1 As DataGridView
    Dim instForm2 As New Exceptions
    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startpayrollButton.Click
        Dim ssql As String = "select MAX(payrolldate) AS [payrolldate], " & _
                 "dateadd(dd, ((datediff(dd, '17530107', MAX(payrolldate))/7)*7)+7, '17530107') AS [Sunday]" & _
                  "from dbo.payroll" & _
                  " where payrollran = 'no'"
        Dim oCmd As System.Data.SqlClient.SqlCommand
        Dim oDr As System.Data.SqlClient.SqlDataReader
        oCmd = New System.Data.SqlClient.SqlCommand

        Try
            With oCmd
                .Connection = New System.Data.SqlClient.SqlConnection("Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx")
                .Connection.Open()
                .CommandType = CommandType.Text
                .CommandText = ssql
                oDr = .ExecuteReader()
            End With
            If oDr.Read Then
                payperiodstartdate = oDr.GetDateTime(1)
                payperiodenddate = payperiodstartdate.AddSeconds(604799)
                Dim ButtonDialogResult As DialogResult
                ButtonDialogResult = MessageBox.Show("      The Next Payroll Start Date is: " & payperiodstartdate.ToString() & System.Environment.NewLine & "            Through End Date: " & payperiodenddate.ToString())
                If ButtonDialogResult = Windows.Forms.DialogResult.OK Then
                    exceptionsButton.Enabled = True
                    startpayrollButton.Enabled = False
                End If
            End If
            oDr.Close()
            oCmd.Connection.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            oCmd.Connection.Close()
        End Try

    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
        Dim connection As System.Data.SqlClient.SqlConnection
        Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter
        Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
        Dim ds As New DataSet
        Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime)  as duration INTO scratchpad3" & _
          " FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber" & _
          " where [Exceptions].exceptiondate between @payperiodstartdate and @payperiodenddate" & _
          " GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," & _
          " [Exceptions].code, [Exceptions].exceptiondate"
        connection = New SqlConnection(connectionString)
        connection.Open()
        Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
        _CMD.Parameters.AddWithValue("@payperiodstartdate", payperiodstartdate)
        _CMD.Parameters.AddWithValue("@payperiodenddate", payperiodenddate)
        adapter.SelectCommand = _CMD
        Try
            adapter.Fill(ds)
            If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
                'it's empty
                MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data")
                connection.Close()
                Exceptions.saveButton.Enabled = False
                Exceptions.Hide()
            Else
                connection.Close()
            End If

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
            connection.Close()
        End Try
        Exceptions.Show()
    End Sub

    Private Sub payrollButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles payrollButton.Click
        Payrollfinal.Show()
    End Sub
End Class

and when I run my program and press this button

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click

I have my date range within a time that I know that my dataset should produce a result, but when I put a line break in my code here:

adapter.Fill(ds)

and look at it in debug, I show a table value of 0. If I run the same query that I have to produce these results in sql analyser, I see 1 result. Can someone see why my query on my form produces a different result than the sql analyser does?

Also here is my schema for my two tables:

Exceptions

employeenumber varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS
exceptiondate datetime no 8 yes (n/a) (n/a) NULL
starttime datetime no 8 yes (n/a) (n/a) NULL e
ndtime datetime no 8 yes (n/a) (n/a) NULL
duration varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS
code varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS
approvedby varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS
approved varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS
time timestamp no 8 yes (n/a) (n/a) NULL

employees

employeenumber varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS
name varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS
initials varchar no 50 no no no SQL_Latin1_General_CP1_CI_AS
loginname1 varchar no 50 yes no no SQL_Latin1_General_CP1_CI_AS

I can also verify that the variables are passing the correct values. Can anyone please assist as to why this isnt working?

Thank you

Doug

Dani AI

Generated

Two quick, high‑value checks before anything else:

  • The SQL join in the posted query is almost certainly wrong — it compares the same table/column to itself instead of linking Employees to Exceptions. Fixing that is the most likely single change that will make rows appear. Also avoid using SELECT ... INTO when your goal is to return a resultset to ADO.NET; SELECT INTO creates a table and can introduce permission/behavior differences between Management Studio and an app connection. Finally, confirm the app connection string is pointing at the exact same database/instance you used in SQL Analyzer.

A compact, corrected SQL pattern to use (note aliases, explicit schema and no SELECT INTO):

SELECT x.Employeenumber,
       x.exceptiondate,
       x.starttime,
       x.endtime,
       x.code,
       DATEDIFF(minute, x.starttime, x.endtime) AS duration
FROM dbo.Employees AS e
INNER JOIN dbo.Exceptions AS x
    ON e.EmployeeNumber = x.EmployeeNumber
WHERE x.exceptiondate BETWEEN @Start AND @End;

Practical troubleshooting steps (apply in order):

  • As suggested, make sure the SqlCommand is actually associated with the adapter (use the SqlDataAdapter constructor or set SelectCommand).
  • Capture the integer returned by Fill to see how many rows were added — that tells you whether ADO.NET received a rowset.
  • Print/log the final CommandText and the parameter values you send to the server and paste that exact SQL into Management Studio to compare results. Use fully qualified names (dbo.Table) to avoid schema mismatches.
  • Replace AddWithValue with explicitly typed parameters (SqlDbType.DateTime) if you suspect type/precision mismatches.
  • Confirm the Exceptions form is using the DataSet you fill (ds is local in your handler — either bind that table to the form or pass the DataSet to the form before showing it).

Also check the GROUP BY and column names for typos (e.g., endtime vs. ndtime) and use Using blocks for connections/commands to avoid resource issues. Correct the join first — that alone usually fixes this exact symptom.

Pass the command to the adapter, before filling the adapter just pass the command to it and see...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.