Which date format does T-SQL use? Does it rely on the system date? How can I be sure that my parameters are passed on correctly regardless of system date format. This question comes because of error:
Error converting data type nvarchar to datetime.
The SQL script in part:
CREATE PROCEDURE [dbo].[sz_pipeline04_pipelUpdte_inventory]
-- Add the parameters for the stored procedure here
#myFixDte datetime,
#doInsert bit
AS
BEGIN
The calling c# code:
public static DataTable GridInventory(string strdProcedureName, DateTime fixDate, bool execInsertYN)
{
DataTable dtbl_inventory = null;
try
{
dtbl_inventory = new DataTable();
using (var conn = new SqlConnection(cls_connRegistry.GetConnStrFull()))
using (var command = new SqlCommand(strdProcedureName, conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
command.Parameters.Add("#doInsert", SqlDbType.Bit).Value = execInsertYN;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
dtbl_inventory.Load(dr);
conn.Close();
}
}
catch (Exception datawalile)
{ dtbl_inventory = null; }
return dtbl_inventory;
}
edited question.
The code you've now posted looks correct - except for one thing:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
As I've said in the comments, issues only come up around formatting when you convert to strings. So just do:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = fixDate;
DateTimes (C#) and datetime (T-SQL) don't have a format. You get formatting issues when you convert them into strings. In their native representation, they're usually just a count of a number of events (ticks, milliseconds, etc) since some fixed point in the past. ADO.Net knows how to convert a DateTime into a SQL Server datetime.
If you have remaining conversion issues, it's in code you've not yet shown. But it will, again, be because you're converting away from the correct data type (datetime) and using strings.
This is not valid DATETIME format DD-MM-YYYY.
You can use CONVERT It in following:
DECLARE #myFixDte DATETIME
SET #myFixDte = CONVERT(DATE, N'30-12-2012', 104)
SELECT #myFixDte
Or you can SET It without converting in other format like YYYY-MM-DD
Try this:
#myFixDte = convert(datetime, '30-12-2012', 105)
And check the link provided by #N.Molderf
SQL Server recognizes one format always in same way, regardless which culture it using, and that format is YYYYMMDD.
So you can always use your dates in format 20120202 or 20151225, and SQL Server will parse that parameter using same mask.
Why you didnt tell as above c# datetime, here is a simple example for you how to solve this problem in your case it will be something like this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("dd-MM-yyyy HH:mm:ss");
or this one
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
second one is a default
Related
On the server, the date format is mm-dd-yyyy. On my local machine, the date format is mm/dd/yyyy.
I have the following code:
DateTime FrDate, Todate;
string yy = "2020";
string mm = "04";
string dd = "01";
DateTime.TryParse(mm + "/" + dd + "/" + yy, out FrDate);
And then I am trying to run this query:
select * from helpdesk_tranactions where compl_date `= '" + FrDate.ToShortDateString() + "'
This is working fine when I run on my local machine, where the date format is mm/dd/yyyy.
However, when this code is deployed to the server, the same query is not working (since the date format is mm-dd-yyyy).
The error I get is:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
How can I write this query in such a way that it will work regardless of the system date formatting?
Noooooooo! If you're worried about string formats for SQL date values something has already gone horribly wrong.
The column in your database should be a Date, Timestamp, or DateTime rather than varchar field, and if that's true there is no human-readable format! The data is binary. What you see is a convenience shown to you by your management tool or connection library. If you're not using one of the date types for the column column, you should fix the schema, because it really is broken.
Once you have confirmed or fixed the column so you know it is a DateTime value, you should also be using DateTime variables in the C# code. And once you're doing that, the correct way to include those values in a query looks like this (assuming MySql because of the backtick, but you should also tag the question with the correct database engine):
string sql = "select * from helpdesk_tranactions where compl_date = #compl_date";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#compl_date", MySqlDbType.DateTime).Value = FrDate;
cn.Open();
// ...
}
Notice this assigns the FrDate field directly to the query parameter. There's no conversion in your code to worry about.
This technique is also the best and only truly safe way to avoid certain other types of problem with sql.
Inserting Date and Time from two separate Text Boxes. and concatenating for save to database.
I have seen lots of examples for datetime conversions but didn't get any clue.
advance in thanks
DateTime Datetime = Dateconversion.ConvertToDate(txtDate.Text.Trim());
DateTime time = Convert.ToDateTime(txtTime.Text);
insert into table(date) values('"+Datetime+" "+time+"')
First, never use Convert.ToDateTime directly on user input, since it's going to throw exceptions when the input is not convertible to datetime.
Instead, use DateTime.TryParse or DateTime.TryParseExact.
Second, never concatenate strings to create an sql statement, since it's an open door for sql injections attacks. Use parameterized queries instead.
Your code should look something like this:
DateTime DateTimeValue;
string DateTimeString = txtDate.Text.Trim() +' '+ txtTime.Text.Trim();
if(DateTime.TryParse(DateTimeString, out DateTimeValue))
{
using(SqlConnection con = new SqlConnection("ConnectionString")) {
SqlCommand cmd = new SqlCommand("insert into table(date) values(#Value)", con);
cmd.Parameters.Add("#Value", SqlDbType.DateTime).value = DateTimeValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
I will suggest you to concatenate the strings before converting it to date time object.
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Hope it will help.Please use TryParseExact, do not directly convert user input to date time, can cause serious issues.
This is a very simple question about a confusing circumstance with my C#-App:
Usings:
C# Desktop-App / Mysql 5.5
Whats going on:
My app is selection some data from the db (Select date from mytable). The format for column date is yyyy-mm-dd. After retrieving the data inside my C#-App im getting a culture-sensitive output. In my case in format dd.mm.yyyy. Check out my screenshot from debugging.
Notice: The var listDate is from type string!
My output looks like from type DateTime. But I've never converted it into dateTime. The column(db) date is set to format date.
So why am I getting this format? Is it a db or app problem?
My goal is to get the same format yyyy-mm-dd as inside the db.
Every help appreciated. Thanks very much!!!
EDIT 1:
My code:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
Cant imagine this could be the problem. All this is doing is looping through the output and saving the single columns into different passed lists (params List<string>[])
Using:
Services.DB_Select("SELECT date FROM myTable WHERE something = something")
So everything is kept into strings without any converts. It is only about the select and the output db -> c#. Im selecting a date-format and getting a dateTime value culture-sensitive. How is this possible?
EDIT 2: (SOLUTION)
If I get it like SELECT CONCAT(date) FROM mytable... (telling the db to handle (col)date as a string I get the clean output yyyy-mm-dd !
Without concat I get my dateTime output culture-sensitive. So it has to be a problem with my date-format for the date column. But why - really dont know.
If you want, you can get it like this:
string example = "20.08.2013 00:00:00";
DateTime result = GetDate(example);
By using this method:
public static DateTime GetDate(string stringFormat)
{
var date = stringFormat.Split(' ')[0].Split('.').Select(x => Int32.Parse(x)).ToArray();
return new DateTime(date[2], date[1], date[0]);
}
Since you did not provide how you get the data from DB it's hard to say. There are probably two options - 1) some kind of implicit conversion done when retrieving data, so you get the formatted string from db or 2) you do the conversion somewhere after you get the data.
What you could do is conversion to DateTime
listDate.Select(d => DateTime.ParseExact(d,"dd.MM.yyyy hh:mm:ss",CultureInfo.InvariantCulture)) and then format it back to format that you need.
Better solution would of course be getting the date in DateTime directly from DB. Please post your code for this.
EDIT
The problem there is that sqlreader[i].ToString() - this takes your Culture from Environment and does the conversion. In that case I would check for type of the value and if that is DateTime then use ToString("yyyy-MM-dd") instead of simple ToString()
From documentation:
This method uses formatting information derived from the current
culture. In particular, it combines the custom format strings returned
by the ShortDatePattern and LongTimePattern properties of the
DateTimeFormatInfo object returned by the
Thread.CurrentThread.CurrentCulture.DateTimeFormat property. For more
information, see CultureInfo.CurrentCulture. Other overloads of the
ToString method enable you to specify the culture whose formatting to
use and to define the output pattern of the DateTime value.
Alright, a college of mine told me a solution. At least it sounds logic to me:
The col itself is from type date which is a short version of dateTime. When using a clear select like SELECT date FROM mytable the output will come as a DateTime. Thats why I also get the time-part inside my output.
When going for SELECT CONCAT(date) FROM mytable the value is handled like a string. A workaround I found myself. This will only output the date itself.
Strange behaviour. For sure because I work with this date-formatted-column for a long time. Never had any problems with it.
Thanks a lot for your interest!
Hi i am developing an application, in that i required to store date in sql server 2005 database which is retrieved from a textbox in front end. In front end, user is allowed to pick a date from JQuery UI DatePicker plugin.
Error I am getting is as follows:
String was not recognized as a valid DateTime.
Code i have is:
db.eventDate = DateTime.Parse(txtDate.Text, new CultureInfo("en-US").DateTimeFormat);
Try this code
string yourDate = txtDate.Text;
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.ParseExact(formattedDate , "dd-MM-yyyy", CultureInfo.InvariantCulture);
You should either use DateTime.TryParse(expression) or wrap your call to DateTime.Parse in a try/catch block. Just out of interest, can you post some example dates you're converting ? They are in US format, right ?
you better use DateTime.ParseExact with the correct date time format you set to date time picker
for example if the format is "MM/dd/yyyy" you can do as below
db.eventDate = DateTime.ParseExact(txtDate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Try this..Working fine for me..
Convert.ToDateTime(txtDate.Text,System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
or
Convert.ToDateTime(txtDate.Text);
Hope following code helps you.
Dim dt As New DateTime
Dim txtDateFromUser As String = "04/09/2014"
If DateTime.TryParse(txtDateFromUser, dt) = True Then
Dim connStr As String
connStr = System.Configuration.ConfigurationManager.ConnectionStrings("youConnectionStringName").ConnectionString
'Insert into database
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = connStr
Dim sqlcmd As New SqlCommand("insert into tblDateTime (dtTestDate) values ('" + dt.ToString() + "')")
sqlconn.Open()
sqlcmd.Connection = sqlconn
sqlcmd.ExecuteNonQuery()
End If
Here is the test table I've used:
create table tblDateTime (dtTestDate datetime)
i simply changed the date format of JQuery UI DatePicker in my code. Before it was in UK format so i was getting error while saving data to database. But once i change it to US format it working fine.
I thanks for everyone who reviewed my question and suggested me the answers.
I'm trying to insert the current date to the database and i allways get the message(when i press the button on the form to save to my access database), that the data type is incorect in the conditional expression.
the code:
string conString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\Simon\\Desktop\\save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO obroki_save "
+ "([ID_uporabnika],[ID_zivila],[skupaj_kalorij]) "
+ "VALUES (#ID_uporabnika,#ID_zivila,#skupaj_kalorij)";
OleDbCommand insertCommand = new OleDbCommand(insertStatement, empConnection);
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Char).Value = users.iDTextBox.Text;
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Char).Value = iDTextBox.Text;
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Char).Value = textBox1.Text;
empConnection.Open();
try
{
int count = insertCommand.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
empConnection.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
}
I have now cut out the date,( i made access paste the date ), still there is the same problem. Is the first line ok? users.idtextbox.text?
Please help !
try Changing
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
`insertCommand.Parameters.Add("#datum", OleDbType.Char).Value
= DateTime.Now.ToString("dd MMM yyyy HH:mm");`
( or some other acceptable date format)
Assuming that your database actually holds dates, and not strings, for the date column - I think you're trying to insert char values into your date column.
Change
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
insertCommand.Parameters.Add("#datum", OleDbType.Date).Value = DateTime.Now;
I think you are getting issue due to the date format set in your regional settings and the date format accepted by MS Access.
You can use a specific date format as mentioned in following code.
DateTimeFormatInfo ukDTFomat = new CultureInfo("en-GB", false).DateTimeFormat;
DateTime.Now.ToString("yyyy-MM-dd", ukDTFomat);
You can simplify your OleDb usage by adding parameters like this:
OleDbParameter param = new OleDbParameter("#datum", DateTime.Now);
command.Parameters.Add(param);
This uses the override of the OleDbParameter that takes a string (the parameter name) and an object (whatever the value should be for the parameter). This lets OleDb figure out the correct parameter type for you (and saves you a lot of work typing and changing parameter types).
Update: just noticed this is Jet. All bets are off when it comes to Access, so I'm by no means sure the above will work.
You should use the type OleDbType.Date in the parameter. That maps to a DateTime value in .NET and an OLE date (internally represented as double) in the database. That's what Access uses for storing dates.
With any of the other date formats in OleDbType, it will be converted to a string representation that Access doesn't recognise as a date.
If you use OleDbType.Char the DateTime value will be converted to a string using the current culture in .NET, which may or may not be understood by Access depending on what the culture happens to be. In your case it seems that it was not understood.
Are you sure the problem is the date value? I.e., are the other columns really of type Char? For date values, you should use OleDbType.DBDate but you should also use the appropriate type for the other columns.
EDIT
Tested against an Access database with a date column, the following worked (although stripped the time obviously):
cmd.Parameters.Add( "#DateColumn", OleDbType.DBDate ).Value = DateTime.Now;
As well as (which included the time)
cmd.Parameters.Add( "#TestDate", OleDbType.Date ).Value = DateTime.Now;
EDIT As with the date parameters, you should be passing specific types for the other values:
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Integer).Value = int.Parse( users.iDTextBox.Text );
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Integer.Value = int.Parse( iDTextBox.Text );
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Integer).Value = int.Parse( textBox1.Text );