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.
Related
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...
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())
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
The Bill_Date is saved as a string in the database. Now I want to select the records based on this Bill_Date. So I input two dates ie. fromDate and toDate (which are also in string).
All the date values use the U.S. format mm/dd/yyyy (e.g. 11/28/2011).
So how will be the query?
Firstly, your life will be much easier (and the query much faster) if everything was a datetime.
The query (as it stands) would be:
SELECT *
FROM TABLE
WHERE CONVERT(datetime, BILL_Date, 101)
BETWEEN CONVERT(datetime, #fromDate, 101) AND CONVERT(datetime, #toDate, 101)
CONVERT is detailed here.
If the Strings are in the format YYYY-MM-DD (or any other format, where the dates would be chronologically ordered if you sort by the string) you can use between:
select * from table where Bill_date between fromDate and toDate
If a different date format is used you need to parse the strings and create dates, either in c# or in sql. In Oracle you would use TO_DATE, i assume there is something similar in SQL server.
I'm having a problem with some T-SQL in a SP on SQLServer 2005 comparing dates. I'm running the stored procedure from c# with ADO.Net and passing a the native c# datetime datatype(could this be my issues as I know the ranges are slightly different). I do the following to compare 2 DateTime values in my SP.
CREATE PROCEDURE [dbo].[spGetLikelyMatchedIndividuals_v1]
#ID BIGINT = NULL,
#DOB DATETIME = NULL, ...
WHERE ISNULL(CONVERT(CHAR(8),Ind.[DateOfBirth],112),'') = ISNULL(CONVERT(CHAR(8),#DOB,112),'')
This works fine in most cases but from some reason will fail with some Datetime. This is one datetime value that fails:
1925-07-04
Does anyone have anyidea why this may fail? Also what is the best way to compare two date values without the time component?
Seems like your date compare is correct. It may be other logic that is causing this issue. Perhaps you should paste in more of your stored procedure to find the likely problem.
Better yet, don't do any logic against the table as this will prevent your index from being used.
Let your front end app handle the ensuring that the #DOB variable is in the correct format.
If you're comparing dates on SQL-Server, investigate the DateDiff function.
You can compare two dates quite easily and specify the granularity, eg. to the nearest day or hour or minute or whatever.
In your example, one of your values is a datetime, so convert the other to that type using the Convert function.
You just want to compare the date component? You could compare
FLOOR(CAST(x.[SomeDate] as float)) = FLOOR(CAST(#SomeDate as float))
A lot less string work, and should do the job. Even better; create a 1-day range and use that...
DECLARE #from datetime, #to datetime
SET #from = CAST(FLOOR(CAST(#SomeDate as float)) as datetime)
SET #to = DATEADD(day, 1, #from)
...
WHERE x.[SomeDate] >= #from AND x.[SomeDate] < #to
String operation is expensive at times. Here is an example of selecting dates ignoring the time part without any casting:
Select dateadd(dd,0, datediff(dd,0, yourdatetimeval)) as date_column