I have to write a query to get rows where date is like current date.
I don't want to compare the the time part but only date part.
Like today's date is 2014-05-03
but in table its in datetime as 2014-05-03 10:08:22
i tried [http://www.w3schools.com/sql/func_convert.asp]
but could not do anything..
my query is like
select *from dbo.param where cvdatetime like '2014-05-03%';
but its does not work although if i use
select *from dbo.param where cvdatetime like '%2014%';
it works so i don't get why "like" can't work in the previous case
i just want to compare the date part only not the time part..
like in c# i will take the current date as
string today_n = DateTime.Now.ToShortDateString();
which will give only today's date
the query will be like
string query="select *from dbo.param where cvdatetime like '" + today_n + "%'"
what is the correct way?
also i want that whatever be the system date format query should work like even if system date time format is dd-mm-yyyy hh:mm:ss tt the query should work how can i ensure this?
Adding new requirement what if I need to check date hh:mm: only not seconds
i.e, 2014-05-04 12:00: part only not seconds part
You cannot use like as such on datetime column.
Use the below:
select * from dbo.param where convert(varchar, cvdatetime, 120) like '%2014%';
As, far your second question is concerned, you'll have to use parameterized queries to avoid sql injection attacks.
Using SQL Server 2005 or later, just convert the datetime to date:
select *
from dbo.param
where cast(cvdatetime as date) = '2014-05-03';
Do not think about dates as strings. Think of them as dates, with the string format only used for output purposes. Or, if you have to make an analogy to another type, think numbers. As an example, go into Excel, put a date into a cell. Nicely format it. Then set another cell equal to the value of the first cell (=A1 for example). Format that as a number and you will see some strange number, probably in the range of about 40,000. Excel stores dates as number of days since 1970-01-01. SQL has a similar (but different) storage mechanism.
You can use the following for the current date:
SELECT *
FROM dbo.param
WHERE CONVERT(DATE, cvdatetime) = CONVERT(DATE, GETDATE())
Related
I am working on a new WPF project where a user can fill out fields to submit to an SQLite database in C#. Submission and retrieval of information from the database works fine until the user selects a date range that crosses from September to October and from December to January. Then no records are returned even if there are records in that date range. You can have a date range from January to September and October to December, but if you cross from single digit months to double digit months then nothing is returned.
I know SQLite apparently doesn't have "date" as a datatype but when I created my database it made it with "DATE" and didn't get any problems. I have also made it with "TEXT" but both have the same date range problem. I am using "System.Data.SQLite" to create and query the database.
my command string for querying consists of:
string cmdString = "SELECT * FROM " + table + " WHERE DATE >= '" + dateFrom + "' AND DATE <= '" + dateTo + "'";
dateFrom and dateTo strings formatted as "9/30/2019" and "10/31/2019"
I have tried formatting both dates as "MM/DD/YYYY" but that doesn't help.
I have tried using "BETWEEN" and it doesn't help.
I have tried using the "date" function in SQLite and it doesn't work in C# I guess.
My connection string is:
"data source=" + database + ";datetimeformat=CurrentCulture"
I cannot paste the whole code because it is related to my job.
UPDATE:
Thank you for the responses and answers. I got everything to work after changing my date format to fit SQLite. Another thing I missed was when getting the date text from my date picker widget in WPF it was obviously giving me single digits for dates like "9/1/2019" which caused and after I added in logic to add 0's to my SQLite converter function the date ranges can successfully be found.
I know SQLite apparently doesn't have "date" as a datatype but when I created my database it made it with "DATE" and didn't get any problems.
Unlike other databases the column type in SQLite is very flexible and has little bearing on the how the underlying data is stored. In short you can use virtually any type or even no type at all.
The column type ends of with a derived column type (type affinity) based upon a set of rules DATE, MY_DATE, A_DATE even RUMPLESTILTSKIN all end up with the catch-all NUMERIC type affinity.
However, type affinity doesn't play that much of a role. In fact in SQLite you can store any type of data in any column (bar 1 exception, that being the rowid or an alias of the rowid column).
See Datatypes In SQLite Version 3
However, SQLite does have very powerful date and time functions.
I have tried using the "date" function in SQLite and it doesn't work in C# I guess.
They are part of SQLite, they work with SQLite irrespective of the language used to invoke SQLite commands.
They don't work because of the format. Consider this snippet :-
CREATE TABLE IF NOT EXISTS anothertable (DATE);
INSERT INTO anothertable VALUES ('09/30/2019'),('2019-09-30'),('31/10/2019'),('2019-10-31');
SELECT *, date(DATE), datetime(DATE) FROM anothertable;
The result being :-
The Date and Time functions being useful if the date/time is stored in a recognised format as per :-
Time Strings
A time string can be in any of the following formats:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
As such it is likely best to utilise such formats.
Assuming you use 2019-09-30 (instead of 9/30/2019) then such dates are directly comparable that is WHERE DATE BEWTEEN 2019-09-30 AND 2019-10-31 would work as would
string cmdString = "SELECT * FROM " + table + " WHERE DATE >= '" + dateFrom + "' AND DATE <= '" + dateTo + "'"; (assuming that dateFrom and dateTo were so formatted).
The Reason why 9/30/2019 is greater than 10/31/2019 is that the comparison is textual so the character 9 is greater than the character 1 (comparison is over). Likewise 2/1/1700 is greater then 11/12/2099.
The alternative is to include some relatively complex manipulation e.g. :-
-- An example that would handle dd/mm/yyyy where dd and mm could be either 1 or 2 characters
WITH
-- First CTE gets the day and the rest of the date
ctedaypart AS (
SELECT
rowid AS daypartid,
substr(DATE,1,instr(DATE,'/')-1) AS day_part,
substr(DATE,instr(DATE,'/')+1) AS rest_after_day
FROM mytable
),
-- Second CTE gets the month and the rest of the date
ctemonthpart AS (
SELECT
daypartid AS monthpartid,
substr(rest_after_day,1,instr(rest_after_day,'/')-1) AS month_part,
substr(rest_after_day,instr(rest_after_day,'/')+1) AS year
FROM ctedaypart
),
-- Third CTE expands the day and month the have a leading 0 id less than 10 and joins the parts to form YYYY-MM-DD
expandedparts AS (
SELECT
*,
mytable.rowid AS expandedpartsid,
year||'-'||
CASE WHEN length(month_part) = 1 THEN '0'||month_part ELSE month_part END ||'-'||
CASE WHEN length(day_part) = 1 THEN '0'||day_part ELSE day_part END AS date_in_sqlite_format
FROM mytable JOIN ctedaypart ON mytable.rowid = daypartid JOIN ctemonthpart ON daypartid = monthpartid)
SELECT mytable.* FROM mytable JOIN expandedparts ON mytable.rowid = expandedpartsid WHERE (date_in_sqlite_format) BETWEEN ('2019-01-01') AND ('2019-03-31');
I have to compare a table field that is a date stored as varchar in the format 'dd/MM/yyyy' with a date value, but the comparison fails. I have exception
Conversion failed when converting date and/or time from character string.
I tried converting the date to compare i nstring, like this
string dateFormat = date.ToString("dd/MM/yyyy");
and then write the query like this:
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
But I have this excpetion. Someone can help me? Thanks
First, you should not store dates as strings.
As Panagiotis Kanavos wrote in his comment - this is a serious bug. You can't sort by such a column, you can't search for date ranges, and most important - you can't control if someone enters an invalid value - nothing is stopping someone from entering "Alfredo" to that column.
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.
Second, you should not pass dates from .Net to Sql server as strings. you should pass instances of DateTime as parameters.
The .Net DateTime maps directly to SQL Server's Date.
If you can't change the data type of the column, you can at least convert it to date using the proper convert style (103 in your case).
Here is a better way to do it:
var sql = "select * from TB_RICHIESTE where CONVERT(DATE, [Date], 103) <= #Date";
Then you add the #Date parameter to the SqlCommand:
com.Parameters.Add("#Date", SqlDbType.Date).Value = date.Date;
Use Parameter to pass date values refer #Zohar Peled post. This is the proper method handling date values.
OR
You can pass the date value in ISO format, refer the below code.
string dateFormat = date.ToString("yyyy/MM/dd");
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
I have a field Date type. I'm recording data in the format dd/mm/yyyy.
It's displaying just fine. But when I try to use a filter in my select query it returns me every single row. I tried this:
SELECT *
FROM MyTable
WHERE dt_start >= '01/04/2007'
and
SELECT *
FROM MyTable
WHERE dt_start >= DATE_FORMAT('01/04/2007', "%d/%m/%yyyy")
Now, if I try this, it works perfect:
SELECT *
FROM MyTable
WHERE dt_start >= '2007/04/01'
I know it's the standar MySQL date format on it's Site. But I'd like to know a way to achieve this goal.
The syntax you want to convert your dates is like this:
UPDATE [table name] SET [date field name] = STR_TO_DATE('01/04/2007', '%Y-%m-%d')
That will convert all of our dates to the standard like Gordon Linoff said. IF you want them to look like your dates originally when you pull them out, then you can use dateformat in your query:
SELECT DATE_FORMAT([date field], '%m/%d/%Y') AS myDate FROM [table name]
Does that make sense?
I also agree with Gordon that it's easier to store your dates with the standard format. You can manipulate and compare dates more easily this way.
EDIT
SELECT * FROM [your table] WHERE date >= STR_TO_DATE('01/04/2007', '%m/%d/%Y')
With this, you don't have to change your date types and you can just change the string you want to evaluate against to a date in the where clause. Is that what you wanted?
This has to do with the conversion between dates and strings when you do a comparison. You can put the constant that you want as:
SELECT *
FROM MyTable
WHERE dt_start >= STR_TO_DATE('01/04/2007', '%d/%m/%yyyy') ;
However, I would strongly recommend that you use the ISO standard date format in your queries. This is YYYY-MM-DD. You can output whatever format you like, but using the standard in your queries is a good idea.
I have a GridView that should be populated according to a selected date, so I made the use of the Calendar control.
The problem
Since the Calendar control's selected date is DateTime, unfortunately the selected date in the Calendar seems to be is in the format: dd-MM-yyy example 2013-02-15
while the date field in the Database is of type datetime meaning: dd-MM-yyyy HH:mm:SS.ms example 2013-02-15 09:02:03.253
So there will be no result since the Calendar control and the Database field are of different types.
What i tried
SqlDataSource1.SelectCommand = "Select * from table1 where start_date Like '% " & calendar1.SelectedDate.Date & " %' "
As you can see i worked the sqldatasource in code behind and i made the use of Like But even with the use of Like no results show due to Database having not only date but time too.
I was also thinking to change the sql query itself, and precisely the field start_date, to omit the time (HH:mm:SS.ms) but is it possible to do so?
Edit:
Even if the Calendar Control's selected date and the field in the database are both DateTime, the search won't work because when searching with the Calendar Control its query will be Date and Time example 2013-01-01 00:00:00.000 while in the DB the time is not always 00:00:00 thus the need of Between as the answer below.
You can use a Date to extract records from a database using a DateTime field. I dont think using LIKE on dates is a good idea. Specify From and To date ranges to get one day worth of data:
SqlDataSource1.SelectCommand = "Select * from table1 where start_date >" & calendar1.SelectedDate.Date & " AND start_date < " & calendar1.SelectedDate.Date.AddDays(1)
Or using the BETWEEN operator:
SqlDataSource1.SelectCommand = "Select * from table1 where start_date between " & calendar1.SelectedDate.Date & " AND " & calendar1.SelectedDate.Date.AddDays(1)
Calendar.SelectedDate is DateTime. So just change calendar1.SelectedDate.Date to calendar1.SelectedDate.
Proof: http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.calendar.selecteddate.aspx
Formatting only matters when you are displaying data. Basically, dates are integers and datetimes are floats.
Create a .net DateTime object from whatever is selected in your datepicker. Then convert it to a query parameter which you use in your query.
I have a variable which is datetime type. How can i get the shortdatetostring() as datetime variable type ? I have a column in databae as datetime type. I would like to get the records which are added at a certain day.
Example:
SELECT id FROM database WHERE added like #p1
The parameter of the query is a datetime variable.
Match based on day, month, and year of the date variables. Do not use strings, since matching is slow.
SELECT id
FROM database
WHERE Datepart(yy, added) = Datepart(yy, #p1)
AND Datepart(mm, added) = Datepart(mm, #p1)
AND Datepart(dd, added) = Datepart(dd, #p1)
You could do something like this in order to get all the ids on the 26th of January.
SELECT id FROM database WHERE added >= '2012-01-26' and added < '2012-01-27'
In C# you do like below.
DateTime dt;
string Temp1 = "Your Date";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}
In SQL Server
SELECT id FROM database WHERE Datepart(dd, added) = Datepart(dd, #p1)
Please see below the sample
create table #temp
(
dat datetime,
)
insert into #temp(dat)values(GETDATE())
insert into #temp(dat)values(GETDATE()+1)
insert into #temp(dat)values(GETDATE()+2)
select * from #temp where DATEPART(dd, dat) > 27
drop table #temp
If you are using parameterised queries the format of the datetime type doesn't matter.
Got to remember that "2012-01-26" is a string not a date....
If you need a Date formatted a particular way, then myDateTime.ToString(....), there are several overloads, one of which is simply a format String e.g. "yyyy-MM-dd"
If you want to parse a string into a datetime then DateTime.Parse(...), again there are several overloads.
More on dates after comment
DateTime.Parse("12/31/2012") gives you a datetime type in c#.
It parses the string into a DateTime
MyDateTime.ToString("MM/dd/yyyy") gives you a string of date in the specified format.
"31/12/2012" is not a date, if you want it as a date, then you Parse it into one.
Now which way do you want to go DateTime to a string, or string to a DateTime, or are you asking something completely different?
If you want to only Parse DateTimes trhat are in the format mm/dd/yyyy, you can't because when it's string there's absolutely no way to tell the 6th of August from the 8th of June, unless you assume the format is always mm/dd/yyyy which is pretty much guaranteed to go badly wrong at somepoint, which is why when going from Date to String YYYYMMDD or YYYY-MM-DD are the way to go.
If it's what you want / have to do then
DateTime MyDateTime = DateTime.Parse("12/31/2012",CultureInfo.CurrentCulture);
Pass a string in a format that doesn't fit the pattern and it will throw an exception, NB that would include "31/12/2012".
CultureInfo is in the System.Globalisation namespace.
There area number of options. Current, CurrentUI, Invariant etc. Which one you use depends on how you are setup and globalisation / internationalisation requirements (even if they are none). So using Current Culture, would assume US default regional settings. But if I was to run your code, then "31/12/2012" would work and "12/31/2012" would blow chunks.
If you want to fix the formats no matter what system they are run on then InvariantCulture is the way to go. Don't forget to set the neutral language as well. Hit the assembly button on the Applications tab of the project's property pages. Neutral language is a drop down near the bottom. Presumably you want en-us.
If you don't want the excpetion then it's
DateTime myDateTime;
if (DateTime.TryParse("12/31/2012",CultureInfo.CurrentCulture, out myDateTime)
{
// do something with myDateTime...
}
else
{
// do something about the value not being in the correct format
}
You might be able to simplify this by editing the query, actually. Try
select id from database where cast(added as date) = cast(#p1 as date)
This (effectively) strips the time from added as well as the time from #p1 and compares the dates only.