executing queries with datetime in WHERE clause - c#

I use sql server 2008 R2 as a data store.
Until now on the test machine I had the english version of the software and used to make queries formatting the datetime field as
fromDate.ToString("MM/dd/yyyy");
now I have deployed the database on another server which is in the italian language. I shall change the format in my code to
fromDate.ToString("dd/MM/yyyy");
Is there a way to make the query in a neutral format?
thanks!
EDIT:
I forgot to mention that I am using NetTiers with CodeSmith. Here's a complete sample
AppointmentQuery aq = new AppointmentQuery(true, true);
aq.AppendGreaterThan(AppointmentColumn.AppointmentDate, fromDate.ToString("MM/dd/yyyy"));
aq.AppendLessThan(AppointmentColumn.AppointmentDate, toDate.ToString("MM/dd/yyyy"));
AppointmentService aSvc = new AppointmentService();
TList<Appointment> appointmentsList = aSvc.Find(aq);

You should share the code you are using to execute the query, but I guess you are building a SQL query dynamically using string concats to build the query and the arguments. You should rather use a parameterised query then you can pass the data as a date object and no need to converto a string.
For example if your query could be something like this
DateTime fromDate = DateTime.Now;
SqlCommand cmd = new SqlCommand(
"select * from Orders where fromDT = #fromDate", con);
cmd.Parameters.AddWithValue("#fromDate", fromDate);
...
As a good side effect, this will reduce your risk of SQL injection.
Update: After your edit which does change the question context significantly, and I have to admit that I have Zero knowledge of the .netTiers project. But just out of curiosity have you tried just passing the date instances directly as in the following?
AppointmentQuery aq = new AppointmentQuery(true, true);
aq.AppendGreaterThan(AppointmentColumn.AppointmentDate, fromDate);
aq.AppendLessThan(AppointmentColumn.AppointmentDate, toDate);
AppointmentService aSvc = new AppointmentService();
TList<Appointment> appointmentsList = aSvc.Find(aq);

ISO 8601 Data elements and interchange formats — Information interchange — Representation of dates and times allows both the YYYY-MM-DD and YYYYMMDD. SQL Server recognises the ISO specifications.
Although the standard allows both the
YYYY-MM-DD and YYYYMMDD formats for
complete calendar date
representations, if the day [DD] is
omitted then only the YYYY-MM format
is allowed. By disallowing dates of
the form YYYYMM, the standard avoids
confusion with the truncated
representation YYMMDD (still often
used).
I prefer the YYYYMMDD format, but I think that's because I only knew about that to start with, and to me it seems more universal, having done away with characters that might be considered locale specific.

Personally, I always use yyyy-MM-dd. This also makes it sortable as a string.
However, a date is a date is a date. There's no need to change the date to a string. In .NET, user DateTime.

Related

How to get datetime format of SQL column in C#?

I want to get format of a datetime column to be able to use it in C#. I want to get it and change my variable to this format. I could not find any solution. How to get it? I just want to be able to get the format of existing column and use it as string in C#.
DateTime values in SQL Server are stored as binary values that are not human readable. They are not strings at all.
For C#, you should use the normal .Net primitive DateTime type to talk to the database; NEVER use any string formats; reserve the string for when you output to the user. The ADO.Net library (which also sits underneath other tools like Entity Framework) will efficiently and safely handle transport between your application and SQL Server.
I am building an sql query to search a string value as parameter that comes from frontend.
Great, we can do that. The way we do it to to parse the string to a C# DateTime, and then use the C# DateTime value for the query.
Let me elaborate. I'm worried you're wanting to do something like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= '" + TextBox1.Text "'";
var cmd = new SqlCommand(SQL, connection);
THAT IS NOT OKAY!
It is NEVER okay to use string concatenation to include user data like that. Instead, you must use parameterized queries. And when you do this, one of the things you can do is provide datetime values.
So instead, the code should look more like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= #MinDate";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#MinDate", SqlDbType.DateTime).Value = DateTime.Parse(TextBox1.Text);
But even this is still a little rough, because users will do all kinds of things when entering a date into a raw textbox. You'll be much better off if you can also provide a datepicker that ensures you get a clean input from the user.
All that said, the SQL language does have specific formats for Datetime literal values. You can pick any of these formats and the database will handle it correctly:
yyyyMMdd HH:mm:ss[.fff]
yyyy-MM-ddTHH:mm:ss[.fff]
yyyyMMdd
Note the above formats are very specific and must be followed exactly, but if you do any of these can be cleanly converted to SQL Server datetime values. But again: this is not how the values are stored internally, the need for this should be relatively rare, and it's definitely NOT something you would EVER do for user input.

Convert date type in c# to match sql server 2008 date type

I have retrieved a date from an application and stored it in a DateTime Variable. The format of date is dd/mm/yyyy.
I now want to update a column (with datatype date (yyyy/mm/dd)) in a sql server 2008 database with this date
I have tried the below code, but it's giving me an exception "string was not recognized as valid datetime". Please help to solve this problem.
DateTime date = calExpirydate.SelectedDate;
DateTime date1 = DateTime.ParseExact(date.ToString(), "YYYY/MM/DD", CultureInfo.InvariantCulture);
You don't need to convert it at all if you use parameters (and you should be).
A rough example:
DateTime date = DateTime.Now;
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO table (date) VALUES (#date)";
command.Parameters.Add("#date",SqlDbType.DateTime).Value = date;
I'm using SQL Server here, however the concept is similar across most ADO.NET providers.
Your DateTime variable in the framework is stored in one basic format. The way it appears is just formatting off of the .ToString. It's saying give me your date bit make it look like this. Sql server is similar, it understands the date time variable regardless of how it appears.
If you pass your DateTime as exactly how it is in the framework it will save it correctly. The date and time isn't changing just how it's displayed. Your try parse isn't working though because it's not able to recognize the partial string you're giving it.
You don't even need a new date time variable to see it the way you want. Even if you're successful you will have identical date time variables.
yyyy/MM/dd should be correct
DateTime string format

SQL SAVE DATATIME [duplicate]

This question already has answers here:
Insert, select and update DateTime
(2 answers)
Closed 8 years ago.
I have a table with a Date type. And I want to insert the date in this format: dd-mm-yyyy (ex: 27/10/2014). I already tried with String but the problem is when i want do a search with 2 Dates the SQL just compare the days. I just realy need the day, month and year. And in C# i use DateTime.Now.ToShortDateString(); to retrieve the date and insert in the database.
I used that query to search the dates:
Query:
SELECT *
FROM [TABLE]
WHERE ([COLUMN] >= '25/10/2014' AND [COLUMN] <= '26/10/2014');
Its any way to save the data like the format i want? Then will be more easy to select the data I want.
Sorry for my english, please help thanks.
SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical value.
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
So in your concrete case, I would rewrite that query as:
SELECT *
FROM [TABLE]
WHERE ([COLUMN] >= '20141025' AND [COLUMN] <= '20141026');
to be independent of any language, regional or dateformat settings in SQL Server ....
Never ever save your date and datetime values as strings. And always parameterize your SQL. If you want to make it easy for yourself, use a micro-ORM like Dapper to simplify such operations:
var result = connection.Query(
"SELECT * FROM EXAMPLE where data between #lower and #upper",
new { lower = DateTime.Parse("10/25/14"), upper = DateTime.Parse("10/26/14") });
I also recommend you use concrete data types o return information from the database, so you will not be forced to use dynamic properties.
Yes, for example in MS SQL, you can save the data in datetime2 (or equivalent) and format it on the way out. This approach will allow you to compare the dates.
Steps you can take:
change the Data type for the column at hand from string to datatime
You can apply formatting on the date upon retrieving. For example, users from Europe will have different date structure from users in north America.

issue with date between c# and sql converting

so i have a string "09/15/2014" and in c# it converts it to date:
DateTime from = Convert.ToDateTime(fromdate);
this outputs "9/15/2014" and when I send it over to sql I get this:
select convert(varchar, '9/1/2014 12:00:00 AM', 101)
which doesn't work for me because I need to keep any leading zero's.
help?
If you're worried about the string formats for dates with Sql Server, you're doing it wrong. As a comment to another answer indicates, SQL Server internally stores all dates in a machine-optimized numeric format that is not easily human-readable. It only converts them to a human-understandable format for output in your developer tools.
When sending dates to Sql Server, always use query parameters. In fact, when sending any data, of any type, to Sql Server in an SQL statement, always use query parameters. Anything else will not only result in formatting issues like your problem here, but will also leave you crazy-vulnerable to sql injection attacks. If you find yourself using string manipulation to include data of any type into an SQL string from client code, step away from the keyboard and go ask a real programmer how to do it right. If that sounds insulting, it's because it's so hard to understate the importance of this issue and the need to take it seriously.
When retrieving dates from Sql Server, most of the time you should just select the datetime field. Let client code worry about how to format it. Do you want leading zeros? Great! The Sql Datetime column will at some point be available in C# as a .Net DateTime value, and you can use the DateTime's .ToString() method or other formatting option to convert the value to whatever you want, at the client.
SQL queries use a date and time format which goes like this:
2014-09-15
That's year-month-day. As per the comments below, this may be different depending on the collation you have on your database (see Scott's comment for a more accurate way to describe this and get dates into this format).
DateTime's ToString method has an overload which takes a formatting string. So you can pass the format you want the string to be output to. Try it like this:
string queryDate = from.ToString("yyyy-MM-dd");
And see what you get. Use that on your query.
But if you really want this done right, use parameters. Like:
SqlCommand command = new Command(connection, "SELECT * FROM foo WHERE someDate = #date");
command.Parameters.AddWithValue("#date", from);
// where "from" is your DateTime variable from the code you've shown.
This will save you the trouble of DateTime to String conversions.

How to get datetime records in "dd/mm/yyyy h:m:s" format FROM SQL server 2005?

I want to get records from sql server 2005 in datetime format like this "dd/mm/yyyy h:m:s"
My database date is default datetime format
AttLogId int
...
DownloadLog datetime
I am trying to retrieve the datetime like this:
SELECT AttLogId ,convert(varchar,DownloadLogDate,103) FROM AttLog
ORDER BY DownloadLogDate
but I only get the date and not the time.
I suggest you don't try to get the values in a particular string format. Fetch them as DateTime values and then format them in the .NET code using DateTime.ToString("dd/MM/yyyy H:m:s").
It's almost always worth keeping data in its "natural" data type (date/time here) for as long as possible, only converting to text when you really need to. So your SQL should just be:
SELECT AttLogId, DownloadLogDate FROM AttLog
ORDER BY DownloadLogDate
How you then retrieve the data will depend on how you're talking to SQL (e.g. LINQ to SQL, using SqlDbReader etc). But you should be able to get it as a DateTime and then format it locally. This will make it easier to test, easier to debug, give you more control over cultural aspects (date separators, possibly specifying a standard specifier instead of a custom one, etc).
it is because you are using 103 , so it will give only date .
if you want more format check this :
http://msdn.microsoft.com/en-us/library/ms187928.aspx
According to need, u can try this
SELECT AttLogId , convert(varchar(10),DownloadLogDate,103) +' '+ convert(varchar(8),DownloadLogDate,108) FROM AttLog ORDER BY DownloadLogDate
Note : firstone is for date and second one is for time in H:M:S
hope this help u..

Categories