VB.NET SQL date is changed format in query - vb.net

I've got a date variable that looks like this:
Dim LogDate As Date = Date.Today.AddDays(-1)
the format comes out like: #4/5/2010#
then it goes into a SQL select query as a WHERE clause. When I debug, the query has changed this to '05/04/2010'. I want it to be in the format '04/05/2010' like it is when declared. Any ideas on how I do this?
Hee is the query:
Dim sqlCmd As New SqlCommand("SELECT TOP (100) PERCENT tblBackup.BackupName,
tblBackupArchive.BackupDate, tblStatus.Status FROM tblStatus INNER JOIN tblBackupArchive ON
tblStatus.StatusID = tblBackupArchive.StatusID INNER JOIN tblBackup ON tblBackupArchive.BackupID =
tblBackup.BackupID INNER JOIN tblClient ON tblBackup.ClientID = tblClient.ClientID WHERE tblBackupArchive.BackupDate = '" & LogDate & "' AND (tblBackupArchive.StatusID = 3) ORDER BY
tblBackupArchive.BackupDate DESC", connection)
-- Jonesy

The best way would be to use a SQLCommand object with a suitable named parameter in the where clause - this would make the formatting of the textual representation of the date totally beside the point...
Another approach, if you're using MS-SQL, would be to use a date in the following format:
Where date = '20100504'
Be careful when using dates though - remember that behind the scenes they are DateTimes...
Martin.

Related

Syntax error with Date in sql query

In my program I'm saving date from DateTimePicker into the global variable with
My.Settings.date = dtpDate_do.Value.Date. I'm using this date to compare date from my database but I'm always getting syntax error, no matter what I'm changing.
This is my query:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = " & My.Settings.date & " ORDER BY ID DESC"
Dates in my database are stored in EU format with dots - 17.2.2014. Can anyone provide me some help.
Never ever create your query like that. Always and without any exception use parameters. This avoids both SQL-injection attacts and ensures proper formatting of your parameters.
Sorry for not knowing VB.NET, but it should be similar to this:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = #Date ORDER BY ID DESC"
cmd.Parameters.AddWithValue("#Date", My.Settings.data)
Explanation: Create your query using #ParamName as a placeholder for your parameters. Then substitute your parameters with values. Make sure to either apply a concrete typed value (i.e. not an object) or/and supply the data type otherwise.
Try to use a parameter in the query like this:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = #date ORDER BY ID DESC";
cmd.Parameters.Add(new SqlParameter("#date", dateTimePicker.Value.Date));

Conversion failed when converting the varchar value '08/22/1954' to data type int

I am trying to write stored procedure within my sql command as shown:
Dim tdate As String = Me.PresentDate.Value.ToString("MM-dd-yyyy")
myCommand As New SqlCommand("select c.description as 'provider',b.lastname,
b.firstname, b.middleinitial,convert(varchar(10),b.dob,101) as DOB,
b.chartID,b.sex, d.businessname,d.businessfax from patientappointmentbase as a,
patientlistbase as b,resourcebase as c, locationbase as d where convert(varchar(10),
a.starttime,101) = " & tdate & "
and a.patientid = b.patientid and a.resourceid = c.resourceid and
a.locationid = d.locationid order by provider, lastname, firstname", myConnection)
and when I run this code I'm getting the error as
Conversion failed when converting the varchar value '08/22/1954' to data type int.
You have two primary problems.
The first problem is that the date is being inlined to SQL so that the SQL you are executing looks like:
select ... where convert(varchar(10), a.starttime,101) = 07-07-2013
This is not valid SQL, so you need to wrap the date parameter in single quotes, i.e.
... where convert(varchar(10), a.starttime,101) = '" & tdate & "' and ...
If you wrap it in double-quotes and you have QUOTED_IDENTIFIER set to on, SQL Server will attempt to interpret it as a column name.
The second problem is that you are using two different date formats to compare. Convert using a style of 101 yields a date in the format mm/dd/yyyy. However, you are using a format of mm-dd-yyyy.
This means you are asking SQL server to compare "07/07/2013" with "07-07-2013" which will never be the same. The easiest fix is to change the date format of tdate to match SQL Server's:
Dim tdate As String = Me.PresentDate.Value.ToString("MM/dd/yyyy")
Your concatenated SQL string looks like
convert(varchar(10), a.starttime,101) = 08/22/1954
That's a sequence of division operations that results in a number, not a date.
You want to create a date literal by wrapping the value in quotes.
(or, better yet, use parameters)

VB.NET 2012 : Select rows from DataView querying with 'Date'

I have a table which contains a date column called PurchaseDate
I have a list box which displays the months. When I click a month , I need to query the dataSource and collect the rows which have the purchase date in the SelectedMonth.
dv2 = New DataView(ds.Tables(0), "PurchaseDate LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
This code is not working. Because here PurchaseDate is in Date format like 'MM/DD/YYYY'. I think I need to convert the date into string before using LIKE operator. I also tried using as below. Even then, it didn't go fine.
dv1 = New DataView(ds.Tables(0), "convert(varchar2(20),PurchaseDate,103) LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
Here SelectedMonth will be a string like '01', '10'..
Use Linq to avoid such issues:
Dim selectedMonth = Int32.Parse(lbMonth.Text)
Dim filteredRows = From r In ds.Tables(0)
Where r.Field(Of Date)("PurchaseDate").Month = selectedMonth
' if you need a new DataTable
Dim tblFiltered = filteredRows.CopyToDataTable()
You don't say what database you are using, so these are the culture independent date literals that I use in the same scenario...
Oracle
TO_DATE('18-Dec-2012','dd-Mon-yyyy')
SQL/Server
'18-Dec-2012'
Ms/Access (not culture independent, but it's the only thing MS/Access accepts)
#12/18/2012#
So you might format your SQL to say something like this...
PurchaseDate BETWEEN '1-Dec-2012' AND '31-Dec-2012'

SQL String in VBA in Excel 2010 with Dates

I've had a look around but cannot find the issue with this SQL Statement:
strSQL = "SELECT Directory.DisplayName, Department.DisplayName, Call.CallDate, Call.Extension, Call.Duration, Call.CallType, Call.SubType FROM (((Department INNER JOIN Directory ON Department.DepartmentID = Directory.DepartmentID) INNER JOIN Extension ON (Department.DepartmentID = Extension.DepartmentID) AND (Directory.ExtensionID = Extension.ExtensionID)) INNER JOIN Site ON Extension.SiteCode = Site.SiteCode) INNER JOIN Call ON Directory.DirectoryID = Call.DirectoryID WHERE (Call.CallDate)>=27/11/2012"
Regardless of what I change the WHERE it always returns every single value in the database (atleast I assume it does since excel completely hangs when I attempt this) this SQL statement works perfectly fine in Access (if dates have # # around them). Any idea how to fix this, currently trying to create a SQL statement that allows user input on different dates, but have to get over the this random hurdle first.
EDIT: The date field in the SQL Database is a DD/MM/YY HH:MM:SS format, and this query is done in VBA - EXCEL 2010.
Also to avoid confusion have removed TOP 10 from the statement, that was to stop excel from retrieving every single row in the database.
Current Reference I have activated is: MicrosoftX Data Objects 2.8 Library
Database is a MSSQL, using the connection string:
Provider=SQLOLEDB;Server=#######;Database=#######;User ID=########;Password=########;
WHERE (Call.CallDate) >= #27/11/2012#
Surround the date variable with #.
EDIT: Please make date string unambiguous, such as 27-Nov-2012
strSQL = "SELECT ........ WHERE myDate >= #" & Format(dateVar, "dd-mmm-yyyy") & "# "
If you are using ado, you should look at Paramaters instead of using dynamic query.
EDIT2: Thanks to #ElectricLlama for pointing out that it is SQL Server, not MS-Access
strSQL = "SELECT ........ WHERE myDate >= '" & Format(dateVar, "mm/dd/yyyy") & "' "
Please verify that the field Call.CallDate is of datatype DATETIME or DATE
If you are indeed running this against SQL Server, try this syntax for starters:
SELECT Directory.DisplayName, Department.DisplayName, Call.CallDate,
Call.Extension, Call.Duration, Call.CallType, Call.SubType
FROM (((Department INNER JOIN Directory
ON Department.DepartmentID = Directory.DepartmentID)
INNER JOIN Extension ON (Department.DepartmentID = Extension.DepartmentID)
AND (Directory.ExtensionID = Extension.ExtensionID))
INNER JOIN Site ON Extension.SiteCode = Site.SiteCode)
INNER JOIN Call ON Directory.DirectoryID = Call.DirectoryID
WHERE (Call.CallDate)>= '2012-11-27'
The date format you see is simply whatever format your client tool decides to show it in. Dates are not stored in any format, they are effectively stored as a duration since x.
By default SQL Uses the format YYYY-MM-DD if you want to use a date literal.
But you are much better off defining a parameter of type date in your code and keeping your date a data type 'date' for as long as possible. This may include only allowing them to enter the date using a calendar control to stop ambiguities.

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using