• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 656
  • Last Modified:

SqlClient.SqlDataAdapter(strSQL, connection) - with a Date as a string :(

I have made a simple form with a Crystal Reports control embedded, with the simple simple code below to bind some data to it.
=====================================

  Dim daT1, daT2 As SqlClient.SqlDataAdapter
        Dim LACARSDataSet As DataSet
        Dim strSQL As String
        Dim connection As New SqlConnection(DataDB.GetConnStr)
        connection.Open()

        LACARSDataSet = New DataSet


        strSQL = "SELECT * FROM client WHERE ClientID = '" & intClientID & "'"
        daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
        daT2.Fill(LACARSDataSet, "client")


        strSQL = "SELECT * FROM driver"
        daT1 = New SqlClient.SqlDataAdapter(strSQL, connection)
        daT1.Fill(LACARSDataSet, "driver")

        If AllThisMonth Then
            'strSQL = "SELECT * FROM job WHERE PickupDateTime > DateAdd(Month, -2, " & DateTime.Now().ToShortDateString() & ")"
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToShortDateString() & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        Else
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & dtFrom.ToShortDateString() & "' AND PickupDateTime < '" & dtTo.ToShortDateString() & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        End If



        Dim rpt As New ClientsReport
        rpt.SetDataSource(LACARSDataSet)
        CrystalReportViewer1.ReportSource = rpt

        connection.Close()


=====================================

If you look in the " If AllThisMonth Then" if statement you will see that with this simple code I am trying to display only a specific date range in the Crystal Report.

However...

strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToShortDateString() & "'"

Creating an SQL string like this would work well in something that queries a DB directly, BUT
with the SqlDataAdapter, I have compile errors with the date string if its not in .ToShortDateString and when it is it plain just doesnt have an effect.
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")

I can only assume that SqlClient.SqlDataAdapter(strSQL, connection) does not know who to convert a sstring of a Date into an actual date as I would be able to normally.

I've explained this poorly, but I've no real understanding of why the DataSet wont fill the data with the correct time-relevent records and why with this simple code (i am new to CR and merely want this one report to show with no hassle) the date cant be read as a string.

I hope someone understands my ramblings and can help. Thanks.
0
deecree
Asked:
deecree
  • 2
  • 2
  • 2
1 Solution
 
grayeCommented:
The DateTime format for SQL Server wants the "medium" date format

.ToString("MMM d yyyy")

0
 
deecreeAuthor Commented:
System.Data.SqlClient.SqlException was unhandled
  Class=16
  ErrorCode=-2146232060
  LineNumber=1
  Message="Conversion failed when converting datetime from character string."
  Number=241
  Procedure=""
  Server="localhost"
  Source=".Net SqlClient Data Provider"
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlDataReader.HasMoreRows()
       at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
       at System.Data.SqlClient.SqlDataReader.Read()
       at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)
       at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
       at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
       at LACARS.ReportsClients.DoReport() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\LACARS\LACARS\ReportsClients.vb:line 48
       at LACARS.ReportsClients.btnGo_Click(Object sender, EventArgs e) in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\LACARS\LACARS\ReportsClients.vb:line 116
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at LACARS.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
==========================

This gives me this above exception at line;
            daT2.Fill(LACARSDataSet, "job")

in this If statement...

        If AllThisMonth Then
            'strSQL = "SELECT * FROM job WHERE PickupDateTime > DateAdd(Month, -2, " & DateTime.Now().ToShortDateString() & ")"
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToString("MMM d yyyy") & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        Else
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & dtFrom.ToString("MMM d yyyy") & "' AND PickupDateTime < '" & dtTo.ToString("MMM d yyyy") & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        End If

====================

This is the exception i was alluding at in the first post.
0
 
grayeCommented:
Humph... that should have worked.

Add a break (or a debug.print) to display the final value for strSQL to make sure it appears formatted correctly.
0
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 
deecreeAuthor Commented:
SELECT * FROM job WHERE PickupDateTime > 'jul 29 2006' AND PickupDateTime < 'oct 29 2006'

I believe this is correct. I have been working on this on and off for about 2 weeks now and growing extremely bitter. Please help.
0
 
YZlatCommented:
did you try changing it to

SELECT * FROM job WHERE PickupDateTime BETWEEN 'jul 29 2006' AND  'oct 29 2006'

or

or

SELECT * FROM job WHERE PickupDateTime BETWEEN '07/27/2006' AND '10/29/2006'


SELECT * FROM job WHERE PickupDateTime > '07/27/2006' AND PickupDateTime < '10/29/2006'
0
 
YZlatCommented:
BETWEEN is better to use than <
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now