How to use DateTime with SQL queries? - c#

How should I be using c# datetime values in my C# queries?
Up until now I've been doing the following:
Datetime my_time = new DateTime(2012, 09, 05);
cmd.Parameters.AddWithValue("#date", my_time);
cmd.CommandText = "SELECT * FROM sales WHERE date = #date";
Which has been working fine until this morning when I've been getting null errors when retrieving values from the results set.
I changed my date parameter to grab the short date string from my datetime value like this:
cmd.Parameters.AddWithValue("#date", my_time.ToShortDateString());
And it appears to be working fine again.
What is the correct way of doing this? Obviously I'm converting my datetime value to a string, only (presumably) for the database to convert it back to a datetime before evaluating my equality where clause, which seems a little pointless.
Edit:
I'm using SQL Server Compact Edition and the date field in my example has a precision setting of 8 (date, excluding time right?). Does that mean I was passing the full date with 00:00:00.000 on the end before? How might I pass a datetime value to the database without including the time, without converting to a string first?

You can just try with my_time.Date
cmd.Parameters.AddWithValue("#date", my_time.Date);

Do not pass it as a string or will run in troubles with culture formatting.
Try using SqlDateTime instead.

You're not converting the date to a string - AddWithValue knows it is a date, but it is a datetime, so it has a time component. Do your sales have a time component to them?
SELECT * FROM sales WHERE DateDiff(d, #date, date) = 0

Related

Convert Datetime string to date in SQL Server

I have a datetime data from C# like this
2019-03-20T11:25:32.0342949
I tried to convert it to datetime using cast and it triggers error
select cast('2019-03-20T11:25:32.0342949' as date)
Conversion failed when converting date and/or time from character string.
I guess its because of the T in the string.
I tried format also which of course doesn't work because its not identify it as date.
So how can I convert it properly to date. Without some substring methods to extract the date part.
You have to use DATETIME2 instead of DATETIME:
SELECT CAST('2019-03-20T11:25:32.0342949' AS DATETIME2) -- 2019-03-20 11:25:32.0342949
demo on dbfiddle.uk
The issue is the precision of the milliseconds part of your string value. You are using seven digits on the milliseconds part which is not possible on DATETIME. So you can do two things:
shorten the milliseconds part to three digits and use DATETIME
use DATETIME2 for more precision
Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
source: https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql
There is also a comparison between DATETIME and DATETIME2 on StackOverflow:
DateTime2 vs DateTime in SQL Server
If you need only date this will work
select cast('2019-03-20T11:25:32.0342949' as date) As DATE
If you need date and time this will work
select cast('2019-03-20T11:25:32.0342949' as datetime2) As DATE
Tried in Sql 15 Its working
You have to take advantage of the CONVERT() method. For example, SELECT CONVERT(date, getdate()), with date being the string you just mentioned. In your case, your datetime string takes up 10 letters of string, so you could also do SELECT CONVERT(VARCHAR(10), GETDATE(), 103). The 3rd parameter is the datetime style you want to convert to.
You should not pass datetime as string from C#, this is the correct way to pass:
string sql = "SELECT * FROM table WHERE datevalue= #date";
SqlParameter dateParam = new SqlParameter("#date", SqlDbType.DateTime);
dateParam .Value = dateValue;
SqlCommand command = new SqlCommand(sql);
command.Parameters.AddWithValue("#date", dateParam );
// then execute the command...

fetch date from datetime column in sql

I have a Product table.I want fetch date from datetime column.
I wrote this query.
Query code is here
SELECT Date = CONVERT(DATE, Date) FROM Product
Query is running sql server management studio and returning the correct date but when called from C# the query runs and returns a result but it returns datetime rather than just the date.
So for example if the query:
SELECT Date = CONVERT(DATE, Date) FROM Product
returns 09-02-16 in management studio
the C# code
SqlDataAdapter adr;
adr = new SqlDataAdapter("SELECT Date = CONVERT(DATE, Date) FROM Product", conn);
returns 09.02.2016 00:00:00
What I would like the C# code to return is: 09-02-16
Please help.
based on you comment you may want to try:
SqlDataAdapter adr;
adr = new SqlDataAdapter("SELECT [Date] = convert(VARCHAR,[Date], 5) FROM Product", conn);
The convert(datetime,[date], 5) will ensure you are returning the result as DD-MM-YY
Try with this SELECT CONVERT(date,[Date]) as date FROM Product
Date is a keyword in SQL, so I would avoid using it:
var adr = new SqlDataAdapter("SELECT CAST([Date] AS DATE) AS OnlyDate FROM Product", conn);
Your query is certainly wrong. either you want to do
SELECT CONVERT([DATE], 102) FROM Product
(OR) declare a variable and store the data there like
DECLARE #Date DATETIME;
SELECT #Date = TOP 1 CONVERT([DATE], 102) FROM Product
Assuming you have a column named DATE and you will have to use a proper format string unless you are passing format string as parameter. Though your query is bit unclear.
c# code is running result : 23.11.2015 00:00:00
How are you seeing this and where? In the debugger in VS? On the screen?
It is probably just formatting based on your culture (the one set on your PC). You are probably not understanding the difference between viewing the string representation in C# of a DateTime object, which can be formatted based on your locale, and the default ISO formatting in Sql Server.
Also there is no such thing in c# as just a date object, its always a date with time (DateTime) although the time component will then have 0 values for the time aspects of the object.
In short it is probably working the way it should.
Based on your comment:
I don't have an error. Query code running result: 2015-11-23. But c#
code is running result : 23.11.2015 00:00:00
I assume that your query is already working properly.
However, the format of the date is different!
So all you need to do is to convert the DateTime in your wished format.
Note: Per default the culture of your thread is based on the settings of your computer (In your case, it's dd.MM.yyyy). The result of the query on SQL Management Studio is depending on the column you are selecting (In your case: yyyy-MM-dd).
True code is here :
SqlDataAdapter adr;
adr = new SqlDataAdapter("SELECT LEFT(CONVERT(VARCHAR, Date, 120), 10) from Product", conn);

datetime query in SQL

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())

Parse DateTime Parameter

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.

Oracle date formatting

in my c# programme i am requesting data from an oracle database and one field is the date abd time in this format - 12/09/2008 15:11:17 , is there anyway i can just return the date?
Is there also a way of ensuring its in british format, by modifying the sql to be dd/mm/yyyy
thanks
You could get the date part of the DateTime using C#, You could do
string date = MyDateTime.ToString("dd/MM/yyyy");///let MyDateTime be your DateTime variable
If you want to do in Oracle, you can use to_char for example,
select to_char(sysdate, 'dd/MM/yyyy') From dual;
The Oracle trunc() function removes the time part:
select trunc(datecol) from mytable;
In your sql query to oracle you can
to_date('12/09/2008 15:11:17', 'dd/MM/yyyy')
where you replace the date with your field in the oracle db.
Alternatively, you can handle it on the C# side with formatting
CultureInfo ukCulture = new CultureInfo("en-GB");
//this assuming you do not have a datetime type
DateTime myDateTime = DateTime.Parse("12/09/2008 15:11:17", ukCulture.DateTimeFormat);
string result = myDateTime.ToString(ukCulture.DateTimeFormat.ShortDatePattern));

Categories