Sql Server Select Only Date Part From DateTime - sql

I have problem in Sql Server for select only date part from DateTime.
The value of DateTime is 2014-05-01 00:00:00.000.
If tried this query I don't have error and the output is correct:
SELECT CONVERT(VARCHAR(10),'2014-05-01 00:00:00.000',110)
2014-05-01
If tried this other query in the doTable:
SELECT
TOP 100 *
FROM
[n].[a2].[DOTABLE]
WHERE
CONVERT(VARCHAR(10),data,110) > DATEADD(DAY, - 1, getdate())
ORDER BY
data DESC;
I have this error:
SQL Server Error Messages - Msg 242 -
The conversion of a char data type to a datetime data type
resulted in an out-of-range datetime value.
The version of SQL server is:
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)
Oct 14 2005 00:33:37
Copyright (c) 1988-2005 Microsoft Corporation
Standard Edition on Windows NT 6.1 (Build 7600: )
I suppose I'm not doing right but I know why.

I think the following is a better way to do what you want:
where date >= dateadd(day, 0, datediff(day, 0, getdate()) - 1)
This truncates the current date to midnight yesterday, which I am guessing is what you really want.
For your method, try using format 120:
SELECT TOP 100 *
FROM [n].[a2].[DOTABLE]
WHERE CONVERT(VARCHAR(10), data, 120) > DATEADD(DAY, - 1, getdate())
ORDER BY data DESC;
You can do this on both sides:
SELECT TOP 100 *
FROM [n].[a2].[DOTABLE]
WHERE CONVERT(VARCHAR(10), data, 120) > CONVERT(varchar(10), DATEADD(DAY, - 1, getdate()), 120)
ORDER BY data DESC;
This format is YYYY-MM-DD which is useful for comparisons.
Then, upgrade SQL Server, and use the date data type instead.

Verified your query in SQL server 2008. It's running fine may be a specific issue related to SQL server 2005 for conversion between varchar and date time.
You can add explicit conversion to date type here
SELECT
TOP 100 *
FROM
[n].[a2].[DOTABLE]
WHERE
CAST( CONVERT(VARCHAR(10),data,110) as datetime) > DATEADD(DAY, - 1, getdate())
ORDER BY
data DESC;

My suggestion is to use the following conversion to zero out the date part you don't requre (in this case time):
declare #n int = datediff(day, 0, [some_datetime_col]);
The above part will return the number of days since SQL Server's epoch time, as an integer. Then, to finish off the conversion:
select dateadd(day, #n, 0);
This adds back that number of days, returning a datetime with no time portion. To apply it to your example:
where
datediff(day, 0, data) > (datediff(day, 0, getdate()) - 1)
In your case, you don't need to do the conversion back to datetime as it's just a where clause; you can compare integers pretty efficiently and get the same result.
The added benefit of this method is that you can just as easily apply it to months (get first day of month, for example) and years. More care needs to be taken with weeks, but that's beyond the scope of this answer.

why you convert date to varchar?
try this query
SELECT TOP 100 *
FROM [n].[a2].[DOTABLE]
WHERE data > DATEADD(DAY, - 1, getdate())
ORDER BY data DESC;

Related

SQL Server error in conversion of date from string

NPD.CreatedOn is defined as a datetime datatype column (in SQL Server).
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(MONTH, CONVERT(VARCHAR(7), NPD.CreatedOn, 126), CONVERT(VARCHAR(30), GETDATE(), 126)) <= 6
I get this error:
Conversion failed when converting date and/or time from character string.
What can I try to resolve it?
Don't use things like DATEDIFF in the WHERE on your columns, such queries aren't SARGable and thus can (will) perform poorly. If you want rows where the date is on or after the start of the month 6 months ago then do the date logic on GETDATE()/SYSDATETIME()/etc:
SQL Server doesn't have a "start of month" function, but you can use EOMONTH and then add a day:
SELECT *
FROM dbo.NPDMaster NPD
WHERE NPD.CreatedOn >= DATEADD(DAY, 1, EOMONTH(GETDATE(),-7));
You don't need to convert the datetime values to text. DATEDIFF() expects datetime values as second and third argument:
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(month, NPD.CreatedOn, GETDATE()) <= 6
The actual reason for the error (as is explained in the documentation), is that ...DATEDIFF implicitly casts string literals as a datetime2 type.

Convert time from British to American format

I have the below code which is failing at the 'CAST('10-10-2014' AS DATETIME)', please can someone assist?
SELECT Sum(poval)
FROM iesa_dwhs.dbo.vw_an_purch_bkb_010_sources vw_AN_Purch_BKB_010_Sources
WHERE Upper(plant) = Upper(('0LH0'))
AND dt BETWEEN Cast('10-10-2014' AS DATETIME) AND Getdate() - 7
AND Upper(matcat) = 'CODED'
Read the documentation. Be explicit about your conversion:
select british_style_datetime = convert(datetime, '23-10-2015 20:15:10.123' , 103 )
If you are not explicit about it, the conversion will be done per the configured settings for the SQL Server instance in question. And if the date/time string is non-ambigous, the conversion is likely to fail, with something like this:
select convert(datetime, '23-10-2015' )
producing (on my SQL Server):
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type
resulted in an out-of-range value.
And if the conversion is ambiguous, the operation will probably succeed, but you're likely to get an incorrect value, with something like
select convert(datetime, '11-10-2015' )
producing (on my SQL Server):
2015-11-10 00:00:00.000
Are you sure dt it a datetime?
The safe bet is yyyy-mm-dd as that only has one mm dd format
All this works for me
select Cast('10-10-2014' AS DATETIME)
select Cast('2014-10-10' AS DATETIME)
select GETDATE()
select GETDATE() - 7
select 'yes'
where Cast('2014-10-15' AS DATETIME) between Cast('2014-10-10' AS DATETIME) AND Getdate() - 7
select 'yes'
where Cast('10-12-2014' AS DATETIME) between Cast('10-10-2014' AS DATETIME) AND (Getdate() - 7)
If you're using SQL Server 2014 or newer, you can use the DATEFROMPARTS function. Then you won't need to worry about the format.

only retrieve record from sql database which have todays's date

I'm using SQL SERVER 2008 R2 to store data and C# web application to retrieve data and display it into gridview.
I have already stored data with different dates Now I want to show data daily on C# gridview according to date like : as today is 15 august and data having date as 15 august only populate the gridview.
I have created the datasource to populate the gridview which previously shows all the data irrespective of date:
code is as follows:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LoginConnectionString %>"
SelectCommand="SELECT * FROM [Student]"></asp:SqlDataSource>
Now I want to just show only current date/todays date data as explained above.
Please guide me how to write the sql command to achieve the above functionality.
Table name is Student
Column Name is date stored as datetime
Thanks
Assuming that "date" also contains time of day information, you have to strip it when comparing to current date:
WHERE CAST(Student.[Date] AS DATE) = CAST(GETDATE() AS DATE)
Add your where clause to your select statement like this:
Where Cast(Student.Date As Date) = Cast(GetDate() As Date)
Edit: updated to use the cast instead of convert, and made it so it's only equal to today's date.
Better than casting the column as a date, IMHO, would be to use an open-ended range:
DECLARE #today DATE = GETDATE();
SELECT
...
WHERE column >= #today AND column < DATEADD(DAY, 1, #today);
Some background info on why you don't want to convert to string and why, in most cases, you want to avoid applying functions to columns.
You can use DATEDIFF
SELECT * FROM tablename where datefield = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
EDIT
I can not check at the moment but you can adjust and pull all dates between dates with a query like the one below.
SELECT * FROM TEST_NAMES
where Date < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
and
Date >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
EDIT
Got around to testing. You can account for the timestamp differences you can convert the field to a VARCHAR and use the below query.
SELECT * FROM tablenames
where CONVERT(VARCHAR(10), Datecolumn) = CONVERT(VARCHAR(10), GETDATE())

How to only check the time on datetime fields but ignore the date?

I have a column that stores data in datetime format. I want to check for all instances where the time part of this column is not equal to 00:00:00:000 - the date does not matter.
Basically, if time() was a function, something like this:
SELECT *
FROM progen.DY
WHERE TIME(DY_DATE) <> '00:00:00:000'
How do I go about doing this?
You only need a minor tweak on what you already have.
SELECT *
FROM progen.DY
WHERE TIME(DY_DATE) <> '00:00:00:000'
Use CONVERT to change your DATETIME to a TIME.
SELECT *
FROM progen.DY
WHERE CONVERT(TIME, DY_DATE) <> '00:00:00:000'
Another way is to convert it to different datatype, eg
SELECT *
FROM progen.DY
WHERE CAST(DY_DATE as float) - CAST(DY_DATE as int) > 0
SQLFiddle Demo
I do this all the time when trying to see if a table's column should be turned into a date instead of a datetime, which is really the answer.
select *
from progen.dy
where cast(dy_date as Date) <> dy_date
the cast removes the time and datetime has higher precedence, so when compared, if the are unequal then it has a time value. Same thing could be done with a cast to time, with a bit of different syntax.
Use DATEDIFF and DATEADD to instead get the date part of the datetime. Compare the column against the date only, and it will return those rows that have a non-zero time.
The way this works is that we first calculate the difference (in days) between the epoch and the value. We add that number to the epoch to create a new datetime. Since the result of DATEDIFF is an integer, any time component gets rounded off.
SELECT *
FROM Table
WHERE DateColumn <> DATEADD(d, DATEDIFF(d, 0, DateColumn), 0)
The time function could then be implemented by the following, not that I recommend it for this specific scenario:
SELECT DATEDIFF(minute, DATEADD(d, DATEDIFF(d, 0, DateColumn), 0), DateColumn) as MinutesIntoDay,
-- or, if you require higher precision
DATEDIFF(second, DATEADD(d, DATEDIFF(d, 0, DateColumn), 0), DateColumn) as MinutesIntoDay
FROM Table
Edit: As mentioned in other answers, you can cast to DATE to achieve the same effect as DATEADD(d, DATEDIFF(d, 0, DateColumn), 0), which cleans up nicely. However, DATE was only added in SQL Server 2008, whereas the formula has compatibility back to at least SQL 2000. So if you need the backwards compatibility or are dealing with SQL CE, casting to DATE is unavailable.
SELECT *
FROM progen.DY
WHERE CONVERT(TIME, DY_DATE - CONVERT(DATE, DY_DATE)) > '00:00'

Please tell me what is error in my date comparison sql query

Please help me to find out error in my SQL query. I have created this query to compare dates
select * from Joinplans jp
where cast(convert(varchar,GETDATE(),103) AS datetime) BETWEEN
CASE(convert(varchar,jp.planstartDate,103) AS datetime) AND
CASE(convert(varchar,DATEADD(DAY,jp.planDays,jp.planstartDate),103) AS DATETIME)
It's giving me the error:
incorrect near 'AS'
I am using SQL Server 2005.
You wrote case instead of cast in two instances.
If planStartDate is actually a date, then there is no need to cast it to a character column:
Select ...
From Joinplans jp
where GetDate() Between planStartDate And DateAdd(day, jp.planDays, jp.planStartDate)
Now, if planStartDate is storing both date and time data, then you might want to use something like:
Select ...
From Joinplans jp
Where planStartDate <= GetDate()
And GetDate() < DateAdd(day, jp.planDays + 1, jp.planStartDate)
This ensures that all times on the last date calculated via the DateAdd function are included