I have a SQL query being sent by C# system.data.odbc OdbcCommand object.
SELECT Calldate
FROM calls;
The Calldate column is a datetime type.
I want the select statement to only return the date portion of the value. The DateValue function doesn't seem to do anything. I am hoping to achieve this within the SQL provided to the OdbcCommand object.
Edit 1: The resource being queried is an access mdb file.
Given you are using sql server, you can convert the datetime
select convert(datetime, CallDate, x) from calls
x can represent different notations/numeric values for different date formatting. See this link for all the different numeric values, and the examples of their output.
http://linesofcode.net/snippets/45
EDIT (based on the fact that OP is using access, not SQL server)
You can format any string using the MS format function:
SELECT Format(CallDate,'yyyy/mm/dd') FROM calls
more formatting options here: http://www.webcheatsheet.com/SQL/access_functions/format.php
How about -
select datevalue(Calldate) from calls;
Other functions listed here
Related
I'm learning SQL Server and have an update statement where the current date and time are inserted as follows:
UPDATE data_table
SET Date_Time_Cx = CURRENT_TIMESTAMP
When it is populated in the DB, it appears "Feb 22 2018 5:07PM". How do I get to populate with the format "YYYY-MM-DD hh:mm:ss"? I looked through the SQL Server documents and lots of posts and it seems like it should be populating in the desired way. Where did I go wrong? Thanks!
Then change the type of date_time_cx:
alter table data_table alter column date_time_cx datetime2;
Then it should go into the database using the proper types. You can format the value as you wish afterwards.
I'm not sure what this has to do with C#, but here's a solution for you using base SQL.
SELECT convert(varchar, getdate(), 121)
You can find all kinds of different date and time formats from the link below.
https://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
I am building some test scenarios for my application. In order to do this, I have some code that is generating some SQL to help me test properly. A sample of the SQL that is generated is shown here:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
'Sat, 17 Dec 2011 14:33:12 GMT',
'Sat, 17 Dec 2011 15:13:12 GMT'
)
When I attempt to execute this SQL, I receive the following:
Conversion failed when converting date and/or time from character string.
How can i format the date/time strings so that SQL Server 2008 will accept them? I really need my C# code to generate the SQL (including the date/time items) to create my tests properly.
Thank you!
The way to solve this is to use the 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.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 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.
You can use SqlParameters.
So your command would be:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
#CheckInDate,
#CheckOutDate
)
And you'd insert the dates like so:
SqlParameter checkin = new SqlParameter("#CheckInDate", SqlDbType.DateTime);
SqlParameter checkout = new SqlParameter("#CheckOutDate", SqlDbType.DateTime);
checkin.Value = DateTime.Today; // Format these to the desired dates
checkout.Value = DateTime.Today;
command.Parameters.Add(checkin);
command.Parameters.Add(checkout);
A better approach would be to not format dates at all, parameterize your insert statement, and pass dates as command parameters.
here is my query:
select reporttime, datapath, finalconc, instrument from batchinfo
join qvalues on batchinfo.rowid=qvalues.rowid where qvalues.rowid
in (select rowid from batchinfo where instrument LIKE '%TF1%' and reporttime
like '10/%/2010%') and compound='ETG' and name='QC1'
i am running it like this:
// Create a database connection object using the connection string
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
// Create a database command on the connection using query
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
it does not return any results.
when i try this same query in sql server GUI it returns lots of rows
is there a problem specifically with the syntax of the query for c#?
please note that if i simplify the query like select * from table, there is no issue
Can you try using SqlCommand instead of OleDbCommand?
According to MSDN it: Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database.
So if you really are using SQL Server 2008 you should probably use this. Any reason you are not?
How are you setting up the mySelectQuery string?
Could this be a problem with an escape character?
If you're not doing it already,
string mySelectQuery = #"query text here";
Personally I would run query profiler to see what query (if any) is being run, and then go from there.
Are you sure you are connecting to the same database in your code?
On a side note do you need the inner select? Couldn't you write this query as follows.
select reporttime,
datapath,
finalconc,
instrument
from batchinfo
join qvalues on batchinfo.rowid = qvalues.rowid
where compound = 'ETG'
and name = 'QC1'
and batchinfo.instrument like '%TF1%'
and batchinfo.reporttime like '10/%/2010%'
Edit - Never mind, just read the comment that your date is in a varchar field. Will leave this here since it may still be useful information.
Try this:
reporttime like 'Oct%2010%'
I have a test table here and when I query it using
where LastModified like '11/%/2010%'
no rows are returned, although all of the rows in the table have dates in November 2010. When I run the same query using like 'Nov%2010%', it returns all rows.
Details can be found here:
The LIKE clause can also be used to search for particular dates, as well. You need to remember that the LIKE clause is used to search character strings. Because of this the value which you are searching for will need to be represented in the format of an alphabetic date. The correct format to use is: MON DD YYYY HH:MM:SS.MMMAM, where MON is the month abbreviation, DD is the day, YYYY is the year, HH is hours, MM is minutes, SS is seconds, and MMM is milliseconds, and AM designates either AM or PM.
I have a Db server with DateTime fields in the format of "yyyy-MM-dd mm:hh:ss"
I'm trying to use linq2sql to insert a DateTime member to a DateTime field in one of my tables.
When I do it in SQL I convert the DateTime as following:
"Insert into .... Convert(datetime, getdate(), 120) ..."
But when I try to submit the object from Linq the date time inserts in the wrong format.
Is there a way to define the format that will be inserted to the Db in Linq?
Or is it a DateTime object Issue?
You shouldn't be dealing with a string format when you pass dates and times to the database, any more than you would if you were passing a number. The database should be handling all this for you without any conversions. This is true whether you're using LINQ or within the SQL - almost any time you have to manually do string conversions between types at the database level, you should look for a better solution.
If you read the value back out of the database (as a DateTime again) does it have the right value? If not, in what way is it wrong?
Update can't work.
sqlstr ="UPDATE emp SET bDate='"+Convert.ToDateTime(txtbDate.Text)+"'";
can't update emp table.
I tried also using Parse method.
It throws error message :
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated.
You should allways use sql parameters when accepting input from a user. This will probably solve your problem as well as increasing security. Try this:
sqlstr ="UPDATE emp SET bDate=#bDate";
SqlCommand.Parameters.AddWithValue("#bDate", Convert.ToDateTime(txtbDate.Text));
Don't use adhoc SQL like this, use parameterised SQL:
sqlstr = "UPDATE emp SET bDate=#NewDate WHERE...."
Then on your SqlCommand, add the #NewDate parameter:
YourSqlCommand.Parameters.Add("#NewDate", SqlDbType.DateTime);
YourSqlCommand.Parameters["#NewDate"].Value = Convert.ToDateTime(txtbDate.Text);
You can use parameterised stored procedures.
The .net datetime contains more values than the SQL DateTime, so thus the out of range error.
Parameterised stored procs also provide more security against sql injection attacks.
You can kill 2 birds with one stone and use a parameter:
UPDATE emp SET bDate=#newDate
And fill the parameter value with a Date directly, using DateTime.Parse() to do the conversion. This also eliminates the SQl injection problem you have now.
have you tried to parse the date value to SQL format(yyyy-MM-dd), ex 2000-12-31
Convert.ToDateTime(txtbDate.Text).ToString("yyyy-MM-dd");
Cheers.
use Parameters to pass the date to the query
this if you are using ole db:
sqlstr = "UPDATE emp SET bDate=? "
command.Parameters.Add(New OleDbParameter("#bDate", Convert.ToDateTime(txtbDate.Text)))
"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated."
You're date-time is not in the range accepted by the SQL DateTime. What date are you trying to parse? I've this error for some really early dates (1/15/103 for example). Dates are stored in ticks from an arbitrary start point.
The start point for .net is 1/1/0001
The start point for SQL is 1/1/1753
I'm not sure about end values. Try running these and compare. Either code trace, or console writeline.
DateTime netDate = DateTime.MinValue;
SqlDateTime sqlDate = SqlDateTime.MinValue;
DateTime netMaxDate = DateTime.MaxValue;
SqlDateTime sqlMaxDate = SqlDateTime.MaxValue;
Read what everyone else said about parameterizing queries.
it should be plain string because you store it in a sqlstr ;)