Date comparison format in stored procedure - c#

I have a sql server 2005 database and a stored procedure that accepts two dates and does some comparisons on the data #start_date_from and #start_date_to both of which are of type DATETIME.
We are using LINQ to call the stored procedures from our code and dragging the stored procedure onto the LINQ surface generates a method call which accepts nullable datetimes.
The problem that I am facing is that our dates from the user interface are entered as dd/MM/yyyy (we're in Australia) and parsed as a C# DateTime.
Once the call to the stored proc occurs it seems to convert it to an american style date. I'm looking for a way to prevent this, hopefully without having to change the datatype of the parameters in the proc.
I have tried using SET DATEFORMAT dmy in the proc but it seems to have no affect, I assume it must need a GO or something to take effect.
I was considering maybe trying some funky formatting/conversion/casting once inside the stored proc but that seemed like a last resort.
I guess also I could change the input parameters to varchars and put the date in an unambigious format.
Within the proc itself the dates are using with the BETWEEN keyword (if that makes any difference).
So what other options (or which of the ones I've outlined) should I go with?

I guess that user input are implicit converted to DateTime? I would say that you need to parse user input to a valid DateTime before calling the SP.
DateTime.Parse("11/12/1981", new CultureInfo("en-US"));
If the culture is different between users you may want to use the current thread's culture:
DateTime.Parse("11/12/1981", System.Threading.Thread.CurrentThread.CurrentUICulture);

Related

Insert empty DateTime from C# into FoxPro

I am trying to insert an empty DateTime into a FoxPro database using DbParameter in C#. Our application marries FoxPro data along with SQL Server and .NET models/data.
My current issue is that most of our DateTime types in C# are not nullable, nor should they be. However, most of our legacy data in FoxPro are empty dates (shown as ' / / : : '). I am trying to do an insert into the FoxPro table where I do a check to see if the .NET DateTime meets certain criteria, then inserts an empty date. This last part has proven to be a nightmare.
What I have tried so far:
.Parameters.Add(string.Empty, new DateTime())
The above understandably inserts 01/01/0001 but is not what we want.
.Parameters.Add(string.Empty, "{}")
.Parameters.Add(string.Empty, "{:://}")
.Parameters.Add(string.Empty, "{//}")
.Parameters.Add(string.Empty, "'{}'")
The above all result in
System.Data.OleDb.OleDbException: 'Data type mismatch'.
which makes sense because I'm trying to send a string to a field with DateTime type.
Does anyone know how to insert an empty DateTime into FoxPro?
If I'm understanding you correctly, you're not using a DbParameter, but rather an OleDbParameter, and you're adding them through the OleDbParameterCollection.Add method?
If so, consider that you are using the overload that is .Add(String, Object), and you could instead use the overload that is .Add(String, OleDbType):
.Parameters.Add(string.Empty, OleDbType.Date)
The default value of an OleDbParameter is null, so you don't need to do anything more for your empty dates.
Also, depending on how the column is defined in your FoxPro database schema, it may be appropriate to pass OleDbType.Date, OleDbType.DBDate, OleDbType.DBTime, or OleDbType.DBTimeStamp. The full list of OleDB types is documented here, but I'm not entirely certain how they align to FoxPro's data types.
I believe your second example is close, but you have the Date and Time portions reversed.
It should be .Parameters.Add(string.Empty, "{//::}")
The // represent the Date portion, and the :: the Time portion.
Not sure of your SQL-Insert statement for VFP, but you MAY need to adjust it and do TWO different inserts. One IF a date exists, another if it does not.
For the one that does NOT have a date, I would hard-enter the following (for example where the "?" are the parameter place-holders)
insert into yourTable ( fld1, fld2,..., YourDateField ) values ( ?, ?, ..., ctot('') )
the function CTOT() means character to datetime and an empty string will comply with expected VFP Date/time field.
Work for me.
Parameters.AddWithValue("CreateDate", new DateTime(1899,12,30,0,0,0));

How to retrieve Timestamp value from SQL Server using DataReader

How to retrieve Timestamp value(eg:0x000000048E18B9D8 ) from SQL Server using DataReader? I'm getting an IndexOutOfRangeException when doing like this
DateTime date = reader.GetDateTime(reader.GetOrdinal("Timestamp"));
Can anyone help on this?
Also I want to know how to pass timestamp parameter to stored procedure using .Net code
IndexOutOfRangeException thrown on reader.Getordinal() suggests that a column called Timestamp doesn't exist. Check your column names again, and replace with the actual value. By default, it will be called timestamp, but only if you haven't specified a column name.
You could also try string ts = reader["timestamp"].toString(), and make sure it returns something.
According to MSDN, a TIMESTAMP data type is "8 bytes...[and]... just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type."
Therefore, reader.GetInt64() is probably close, if you really need this value, but byte[] myTimestamp = reader["timestamp"] is probably better.
As far as passing it back to your stored procedure, you can create a new parameter with SqlDbType.Timestamp. The value will be a byte array, or, if you have it stored as a string, you could try something like:
cmd.Parameters.Add("#TimeStampParam", SqlDbType.Timestamp).Value = System.Text.Encoding.ASCII.GetBytes(myTimestampStr);`
(NB: I haven't tested this, but it should be close enough).
Note that TIMESTAMP is deprecated, and ROWVERSION is not the preferred syntax.

C# Program want to select data <= 23:59:59 but ends up selecting data with 00:00:00 timestamp as well

this is my first question so pardon any mistakes that might occurs :)
I made a C# program that collects data from SQL Server Database using Datatables, and then export the results to Excel spreadsheets using Interop.
The program itself runs well and doing as it should; however, I found some bugs when it tries to select data with Date columns less than or equal to i.e. 2014-05-31 23:59:59.
Supposed I tried to get all data up to May 1st 2014.
My code first initiates the "Start Date" parameter for the SQL Command later used like this:
var firstDay = new DateTime(today.Year, today.Month, 1); //2014-05-01 00:00:00`
based on firstDay, it initiates the date for the parameter
var periodTo = firstDay.AddSeconds(-1);`
I debugged and got the time I wanted: 2014-04-30 23:59:59
After adding some more parameters for the data criteria, it executes the method to run the query using the parameters supplied.
queryResult = medicore.GenerateRegister(ConfigurationManager.AppSettings["queryDir"], ConfigurationManager.AppSettings["queryName"]);`
The periodTo parameter will be mapped to #EDate variable in the SQL Script. #EDate is declared as Datetime. The #Edate comes into play here:
Select columns
From tables
Where Voucher.Date <= #EDate
which I suppose, the script will be looks like Where Voucher.Date <= '2014-04-30 23:59:59'
The problem is, the result in the Excel file generated also consists of data from '2014-05-01', which is not supposed to be there...at least based on the criteria I set.
Is there some kind of rounding happened between C# and SQL Server?
Thanks!
The reason for this is probably that Voucher.Date is a SMALLDATETIME, therefore you are implicitly converting '2014-04-30 23:59:59' to a SMALLDATETIME:
SET DATEFORMAT MDY;
SELECT CONVERT(SMALLDATETIME, '2014-04-30 23:59:59')
Which gives '2014-05-01'.
Why not just use the Less than operator, instead of less than or equal to?
SET DATEFORMAT MDY;
SELECT ...
WHERE Voucher.Date < '2014-05-01';
N.B I have explcilty stated the DATEFORMAT because yyyy-MM-dd (despite being an ISO standard) is not culture invariant for the DATETIME and SMALLDATETIME data types in SQL Server, and if (like me) you are in a country where the default date format is DMY then SELECT CONVERT(SMALLDATETIME, '2014-04-30') will give you a conversion error. yyyyMMdd is the only culture invariant date format for these two types.
An excellent, and very relevant article to read is Aaron Bertrand's Bad habits to kick : mis-handling date / range queries

Error in inserting statement when inserting

I am working on c# project and using winform.
Here the problem is the query was working previously but now it is not working
Here the todaydate is a datetimePicker which is set to short date format
and my datatype of column is smalldatetime the error i am getting is
The conversion of a nvarchar data type to a
smalldatetime data type resulted in an out-of-range value.
The statement has been terminated.
if i have two date time picker one for date and second for time then how can i insert? please can you guide me
AddWithValue determines the datatype of the parameter from the value you pass.
In your case you are passing a string and thus the parameter is passed to the database as a string not as a datetime expected by the database
you should change that line
cmd.Parameters.AddWithValue("#today", todaydate.Value);
You're currently passing in the text value, which means something else is having to then parse it as a date. Don't do that. Given that you've got a DateTimePicker, you should just use the DateTime value it provides:
cmd.Parameters.AddWithValue("#today", todaydate.Value);
... or create the parameter first with a specific type (SqlDbType.SmallDateTime), then set the value using todaydate.Value. The important point is to avoid the string conversion.
Wherever possible, you should avoid converting values into text. Keep them in their "natural" form (e.g. DateTime in this case) for as much of the time as possible: on input, parse into the natural form, and if you can avoid ever converting to a string, do so!
I think your time7 column in database is smalldatetime and you tried to assign it a string. I don't suggest it.
Try with Add() method like this;
command.Parameters.Add("#today", SqlDbType.SmallDatetime);
command.Parameters["#today"].Value = todaydate.Value;
or you can use AddWithValue() as also like this;
cmd.Parameters.AddWithValue("#today", todaydate.Value);

How to change date format in mysql stored procedure insert statement "22-12-2010" to "2010-12-22"

I send the registration date parameter to mysql database like "22-12-2010". But my sql date date type is in another format how can I change the date format like "2010-12-22" also I have to insert this into table.
Give code in C#,asp.net code behind either sql query statement!
Use this comprehensive MSDN pages as your guide: Standard Date and Time Format Strings and Custom Date and Time Format Strings.
There are many examples on those pages on how to reformat a date string in C#, and they also provide a good clear explanation on how date formatting works in the DateTime class.
Once you've reformatted your date string in C#, you should be able to pass it on down without needing to use SQL to reformat it.

Categories

Resources