Convert time from British to American format - sql

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.

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 varchar containing various formats to DATETIME

I have a record_created column of type varchar containing multiple values formatted in two different ways throughout.
2017-04-17 16:55:53.3840460
Sep 18 2015 11:25PM
How can I convert this column into a DATETIME to be compared to GETDATE?
GETDATE() is SQL Server specific if so, then you can use try_convert() :
select cast(try_convert(datetime2, col) as datetime)
from table t
where try_convert(datetime2, col) is not null;
However, if the string date is exactly the same format which you have provide then you can simply do casting :
select cast(cast(col as datetime2) as datetime)
from table t;
If you are using SQL Server, then you may be able to use the CONVERT function here:
SELECT
CONVERT(datetime, LEFT('2017-04-17 16:55:53.3840460', 23), 121) AS date1,
CONVERT(datetime, 'Sep 18 2015 11:25PM', 100) AS date2;
Your first type of timestamp seems to work with mask 121, and the second one works with mask 100. The demo link below shows that the conversions are working.
Demo

Convert a varchar YYYYMMDD into datetime to compare with GETDATE()

What am I doing wrong here? I've looked through other posts but I'm getting different results than other people.
Trying to convert a varchar YYYYMMDD to datetime, and I keep getting:
Msg 8115, Level 16, State 2, Line 2
Arithmetic overflow error converting expression to data type datetime.
Attempts:
CONVERT(DATETIME, EXPDATE)
CONVERT(DATETIME, EXPDATE, 102)
(CONVERT(DATETIME, CAST(EXPDATE AS CHAR(8)), 112))
CONVERT(DATETIME, CAST(expdate AS VARCHAR(8)))
Am I bungling something obvious here?
You clearly have a values that are not valid dates.
In SQL Server 2012+, I would suggest TRY_CONVERT():
TRY_CONVERT(DATETIME, EXPDATE)
Then, look at the values that are NULL to see where data problems may be.
In earlier versions, you should be able to use isdate():
(CASE WHEN ISDATE(EXPDATE) = 1 THEN CAST(EXPDATE AS DATE) END)
I have a similarly formatted date field (DateKey) in a table I use. I convert it to DATETIME using this syntax:
SELECT CAST(CAST(DateKey AS VARCHAR(10)) AS DATETIME) FROM tblDate
Will this work for you?
Excellent. Gordon and chancrovsky, you helped me flush out the values that were formatted incorrectly. I used a version of what you posted and this worked
(CASE WHEN ISDATE(ExpDate) = 1 THEN CAST(ExpDate AS DATE) ELSE NULL
END) as ExpDate
Thank you so much!

Sql Server Select Only Date Part From DateTime

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;

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