How to select only Date value No Time in LINQ to SQL? - vb.net

I need to have a query which list all the user according to the date value in the database. Problems is this, in the database the date format is 5/5/2009 4:30:12 but I want to compare with 5/5/2009. I think the value of the based date is 5/5/2009 12:00:00 and that's why I couldn't query it.
The query is something like
dim db = new databcontext
dim user = from u in db.datacontext where u.signUpTime = 5/5/2009 select u.
May someone please check this problem.
Thanks in advance.

Your theory is correct. You should either use a range in your where clause:
u.SignupTime >= new DateTime(2009,5,5,0,0,0) AndAlso _
u.SignupTime < new DateTime(2009,5,6,0,0,0)
or check only the date:
u.SignupTime.Date = new DateTime(2009,5,5)

Related

SQL: Compare Date Range in a String text field

I have an MS Access db. I am writing an application in C# to access it. I have a field "FileName" of type "Short Text in MS Access. Data in FileName field is like "Test 11-12-2004 15.11.15".
Using a Date Range, I got to search records based on FileName field. I am not able to get - How do I compare the date of this format and retrieve the records ? FileName is a Text type and date is a substring of it. Retrieving only the date part and comparing with >= beginDate && <= endDate seems like a puzzle to me.
Can anyone suggest how do I write SQL query to perform this date range comparision and retrieve those records - "Select * from TestHead where FileName......" ????
Any help is appreciated.
Thanks a lot,
In your C# code, as you are going through the records, I'd split the string like this:
char[] delimiters = {' '};
string[] FileNameParts = FileName.Split(delimiters);
This will result in an array FileNameParts, the second element of which will contain the date, which you can convert to an actual date for use in the query:
DateTime FileNameDate = Convert.ToDateTime(FileNameParts(1))
Something along the lines of:
sSQL = "SELECT * FROM Table WHERE " & beginDate & " <= " & FileNameDate
I see this as preferable to adding a column to your table that contains the date substring of the FileName field, because then you constantly need to be updating that column whenever existing records are modified or new records are added. That means more clutter on the C# side, or an UPDATE query on the Access side which at least needs to get called periodically. Either way it would be more communication with the database.

ADO - Different Date Formats in VB and SQL

Im executing this query in VB:
Dim str As String = "select date_created from TABLE_DATES group by date_created"
Dim cm As SqlCommand = New SqlCommand(str, cn)
..
It's returning the following field in VB:
'11/7/2013 4:30:44 PM'
While in SQL the same field is:
'2013-11-07 16:30:44.917'
So when I send the date from VB to SQL in a query condition, SQL doesn't find the row I asked for.
Any solution to this?
See my answer to another question that will help you ensure your date is always in the correct format. What you do with it, is your decision.

Null exception being thrown by LINQ to EF

This line of code is throwing an exception:
Dim z = (From r In t Where
(DateTime.ParseExact(r.appt_date, "yyyyMMdd", CultureInfo.CurrentCulture).Date.Month _
= myDate.Date.Month) And _
(DateTime.ParseExact(r.appt_date, "yyyyMMdd", CultureInfo.CurrentCulture).Date.Day = _
myDate.Date.Day) And _
(DateTime.ParseExact(r.appt_date, "yyyyMMdd", CultureInfo.CurrentCulture).Date.Year = _
myDate.Date.Year)).ToArray
T is defined as the following:
Dim t = (From p In mydb.C_MYTABLE Select p).ToArray
Since someone is going to ask what I'm trying to do... I have appointment dates stored as strings as yyyyMMdd in a DB, i can not change the DB. I need to be able to filter and sort them by date on the app level. Its my understanding that LINQ will not support conversions inside the query?
(This answer doesn't actually explain your NullReferenceException - but it gives an alternative approach.)
Given that you're checking for an exact date wouldn't it be easiest just to format myDate as yyyyMMdd before the query, and then have:
Dim z = (From r in t Where r.appt_date = formattedDate).ToArray
? That allows you to filter by a specific date - and if you need to filter to a range of dates, I'd expect that you could just use CompareTo. Your dates are in a sortable format, so if you need to find everything between (say) January 10th 2012 and September 20th 2013, you can just say that the string has to be "greater than or equal to" 20120110 and "less than or equal to" 20130920. You can also use this property for sorting - just ordering by the textual representation will be fine.
(That said, if there ever is a database redesign, please urge whoever's responsible to use a more appropriate data type!)
Enity framework its self will not support this. You can howerver select all of the rows out of the database and then sort them at the application level. Like so :
r
.ToList()
.Select(o => new
{
data = o,
appt_date = DateTime.ParseExact(r.appt_date, "yyyyMMdd", CultureInfo.CurrentCulture)
})
.Where(o => o.appt_date < DateTime.Now)
.OrderBy(o => o.appt_date);
This has a very big downside of selecting far to much out of the database.
Alternatively you could format your date into a string and use it to filter within the database and then parse the date:
var formatedDate = DateTime.now.ToString("yyyyMMdd");
r
.Where(o => o.appt_date == formatedDate)
.ToList()
.Select(o => new
{
data = o,
appt_date = DateTime.ParseExact(r.appt_date, "yyyyMMdd", CultureInfo.CurrentCulture)
})
.OrderBy(o => o.appt_date);
Ideally however I ask to improve the quality of the data. If you cant change the 'appt_date' to a Date type can you ask to insert a new column with the correct data type?
I need to be able to filter
You appear to be creating a non-sargable query.
I would suggest that instead of parsing the column you are querying on, create a variable that matches the value you are looking for.
dim myDate = DateTime.Now.ToString("yyyyMMdd");
Dim z = (From r In t Where
(r.appt_date = myDate)).ToArray
and sort them by date
The way the DB is storing the value should look like:
20120101 // Jan 01, 2012
20121231 // Dec 31, 2012
20130101 // Jan 01, 2013
20131231 // Dec 31, 2013
Natural string sorting will sort these in the correct order every time (asc, desc), so .OrderBy() and .OrderByDescending() will work as expected.

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'

Checking for date overlap across multiple date range objects

I have several records in a database that have Start and End Dates
09/15/2011 - 09/30/2011
10/15/2011 - 10/22/2011
11/01/2011 - 11/15/2011
When user stores a record, I need to make sure dates don't overlap.
My simple code checks date ranges within a specific record (e.g. user enters 9/16/2011 or 10/21/2011, I throw an exception.)
But, on the slim chance a user gets creative (e.g. 10/14/2011 - 10/23/2011 or even 10/14/2011 to 11/16/2011), now they have circumvented my check.
BTW, the user could enter 10/14/2011 to 10/23/2011 if they were editing the record that contained values 10/15/2011 - 10/22/2011.
So, I'm trying to solve this riddle with a linq query. However, what I have isn't working exactly right.
UPDATE Nevermind about code not working. While trying to provide an example to expand on Miika's repsonse, I found my answer. So, giving credit to Miika for pointing me in the right direction and posting my working code below:
Here's my code:
Private Sub CheckForOverlap(myMonth As Messages.MyMonth)
Dim am As New MyMonth()
Dim amCollection As Messages.MyMonthCollection
Dim overlappingMyMonthDate As Boolean = False
Dim sErrorMsg As String = ""
'...non-applicable code omitted
Dim query = From s In amCollection _
Let s1 As MyMonth = CType(s, MyMonth) _
Where s1.AttendanceMonthID <> attendanceMonth.AttendanceMonthID And _
(CDate(attendanceMonth.StartDate) < CDate(s1.StartDate) And CDate(attendanceMonth.EndDate) > CDate(s1.EndDate)) _
Select s1
If query.Count > 0 Then
sErrorMsg = "Dates entered surround another entry"
End If
If overlappingMyMonthDate Then
Throw New Exception(sErrorMsg)
End If
End Sub
End Class
It all came down a LINQ query.
Do you need to do it in code or would SQL be an option? If the data is in a database, you could use the following query to check for overlaps.
SELECT COUNT(*)
FROM Table1
WHERE Table1.StartDate < 'endCheckDate'
AND Table1.EndDate > 'startCheckDate'
This will return a count of the number of overlaps found. 'endCheckDate' and 'startCheckDate' are your new query values (in date format). If your data is in a object collection in memory, then you could use LINQ. If you need help with a LINQ statement, let me know.