I'm attempting to take a date contained within a varchar to compare it with getdate() in a where clause. The varchar variable always looks like this:
Last seen: MM/DD/YY
Some sample data:
Last Seen: 07/12/16
Last Seen: 08/01/16
Last Seen: 07/22/16
NULL
NULL
NULL
NULL
Last Seen: 07/28/16
Converting a varchar to datetime and finding the days difference as below works:
datediff(day,CAST(substring(CA_NOTE, 12, 8) as datetime), getdate()) as dayspassed
The problem is, when I stick this coding in the where clause to compare the date to getdate() I keep getting the same error.
where datediff(day,CAST(substring(CA_NOTE, 12, 8) as datetime), getdate()) > 90
Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
date and/or time from character string.
I'm running SQL Server 2014 Management Studio.
Edited to take comments into account
destination-data's suggestion of using TRY_PARSE worked! Thanks everyone.
SQL does not know what to do with getdate()-90 -- subtract 90 days? 90 minutes? 90 years?
You need to use a function such as dateadd, e.g.
where convert(varchar(30),cast(substring(CA_NOTE, 12, 8) as datetime),102) < dateadd(dd, -90, getdate())
The problem is that you're still converting it to a VARCHAR. Try this instead:
CAST(substring(CA_NOTE, 12, 8) as datetime)
Related
Here is db2 date format
1190707 - CYYMMDD
I would like to be able to convert a SQL Server DATE to this format
I found out i can use
SELECT FORMAT(GETDATE(), 'yyMMdd')
but problem now is to get the 1st character which i have no idea what it is
The C is a century digit. And it seems to be based on the 20th century, thus years starting with 19. For years starting with 20, the century digit is one and for the 20th century the century digit is omitted.
This should do the trick
DECLARE #DateToConvert AS DATE
SELECT #DateToConvert = GETDATE()
--SELECT #DateToConvert = DATEADD(year, -100, GETDATE())
SELECT
CAST(
CONCAT(
CAST((DATEPART(YEAR, #DateToConvert)/1000) AS INT)-1,
FORMAT(#DateToConvert, 'yyMMdd')
) AS BIGINT)
I believe this works
SELECT FORMAT(GETDATE(), 'yyyyMMdd') - 19000000
I'm trying to understand how the DATEDIFF function works in SQL Server. The following T-SQL returns -1:
SELECT DATEDIFF(MONTH, 2015-10-25, 2015-12-27)
However, ending_date is after start_date so I would expect a positive number, not a negative number. Further, I would expect that the difference between Oct 25 and Dec 27 to be 2 months. Instead, SQL Server is returning -1 month. Can someone explain what's going on?
You are missing apostrophes:
SELECT 2015-10-25 AS First,
2015-12-27 AS Second,
CAST(2015-10-25 As DateTime) AS [First as datetime],
CAST(2015-12-27 As DateTime) AS [Second as datetime],
DATEDIFF(MONTH, 2015-10-25, 2015-12-27) AS WrongResult,
DATEDIFF(MONTH, '2015-10-25', '2015-12-27') AS CorrectResult
Results:
First Second First as datetime Second as datetime WrongResult CorrectResult
1980 1976 04.06.1905 00:00:00 31.05.1905 00:00:00 -1 2
SQL Server looks at 2015-10-25 as an int - the result of the mathematical expression (1980).
The usage of int in datetime functions cause SQL Server to implicitly convert the int value to a DateTime value.
The int value represents the number of days since '1900-01-01' - and since the second argument results in a smaller int value, you get a negative number.
As Jeroen Mostert wrote in his comment - A gotcha for the books.
You are not quoting your dates, this means your expression evaluates to:
SELECT DATEDIFF(MONTH, 1980, 1976)
Which after implicit conversion to datetime evaluates to:
SELECT DATEDIFF(MONTH, '1905-06-04 00:00:00.000', '1905-05-31 00:00:00.000')
So now the startdate is after the enddate.
Because you're using numbers (integers specifically), not strings. 2015-10-25 = 1980 which, when you convert to a date is '1905-06-04'. On the other hand 2015-12-27 = 1976, which as a date is '1905-05-31'. As '1905-05-31' is one month before '1905-06-04' you get the result -1.
Use literal strings, and yyyyMMdd dates:
SELECT DATEDIFF(MONTH, '20151025', '20151227');
Put the date values within single quotes.
Query
SELECT DATEDIFF(MONTH, '2015-10-25', '2015-12-27');
This query returns 2 as the output.
SELECT
CAST((DATEDIFF(day, '21 JULY 2017', CAST(DAY(DATEADD(mm, DATEDIFF(mm, -1, '21 JULY 2017'), 0) -1) +
LEFT(CONVERT(VARCHAR, DATENAME(MM,'21 JULY 2017'), 120), 10) +
CAST(YEAR('21 JULY 2017') AS VARCHAR(4)) AS DATETIME))) AS INT ) * (2.08 / DAY(EOMONTH('21 JULY 2017')))
I want to calculate the no of day calculation.
But I'm getting an error:
Conversion failed when converting the varchar value 'July' to data type int.
Without knowing what the expected output is, or what is it that you try to calculate, I figured out that the cause to the error you get is that you try to concatenate int values with string values, using the + sign.
In these cases, SQL Server tries to implicitly convert the string values to int values to perform an adding operation (instead of the concatenation operation you want).
Therefor, I've added casting to varchar as well as spaces so that the casting to datetime will work.
Select cast((Datediff(day,'21 JULY 2017', CAST(cast(day(dateadd(mm,DateDiff(mm, -1, '21 JULY 2017'),0) -1) as varchar(10)) +' '+
LEFT(CONVERT(VARCHAR(10), DATENAME(MM,'21 JULY 2017') , 120), 10) +' '+
cast(year('21 JULY 2017') as varchar(4)) as datetime))) as int) *
(2.08/DAY(EOMONTH('21 JULY 2017')))
The output I've got is 0.6709677419350, but since I have no idea what is your goal, I don't know if it's correct.
Since I've had some spare time, I was able to re-write your query and get the exact same results with a much simpler query:
Select Datediff(day,'21 JULY 2017', EOMONTH('21 JULY 2017')) *
(2.08/DAY(EOMONTH('21 JULY 2017')))
I have an issue retrieving the data that I would like. I have a Varchar column that consist of various information. I would like to extract the date from that column only. However, I have been unsuccessful. I used the following SQL(2008) to get the data below, But I can't seem to just get the date only without the time. Obviously, the date and time are in different position. Hope you can help.
SELECT substring(Data, 8, 17)
from mastInfo
9/25/2013 12:36:5
Jul 8 2013 11:40
9/25/2013 12:43:5
SELECT convert(date, Case When IsDate(substring(Data, 8, 17)) = 1
Then substring(Data, 8, 17)
Else NULL END)
from mastInfo
Since you are starting off with a string, it is possible that it does not represent a valid date. Using the IsDate function will return 1 when the string can be converted to a date. Basically, this code will convert to date those values that can be converted, and will return NULL for those values that cannot be converted to a valid date.
If you are using SQL Server 2012 or newer, then you can use Try_Convert().
Here's the SQL Fiddle.
Here's an example (from the above SQLFiddle):
Select Try_Convert(datetime, DateAsString) As DateAsDateTime
,DateAsString
From SomeTable
Here's the result:
DATEASDATETIME DATEASSTRING
September, 25 2013 12:36:05+0000 9/25/2013 12:36:5
September, 25 2013 12:43:05+0000 9/25/2013 12:43:5
July, 08 2013 11:40:00+0000 Jul 8 2013 11:40
if you want convert it to date time use :
SELECT CONVERT(Datetime, '2011-09-28 18:01:00', 120) -- to convert it to Datetime
if you want get time :
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), '2011-09-28 18:01:00', 100), 7))
if you want date part :
SELECT CONVERT (DATE, GETDATE())
what version of sql server?
can you try this:
SELECT convert(date, substring(Data, 8, 17))
from mastInfo
First convert Varchar into DateTime and after that again convert it in varchar in desired date format like 101,102,103
Try this:
select convert(varchar(50),convert(datetime,'9/25/2013 12:43:5'),101)
I have a table that has a TASK_START_DATE and TASK_FINISH_DATE Columns of type datetime
I need help with a query that returns all Tasks when the Task: (date = just the date - I think I can do a conversion to the date from datetime on SQL 2008R2, it works fine)
- is within 2 weeks previous of the current date or two weeks after the current date.
Similarly I also need the records whose TaskEnd values are within 2 weeks previous or two weeks before
I've been trying things like which would get tasks where the start date is within the two previous weeks, but I have to do the same for TASK_FINISH_DATE and I think my and's and or's are all jumbled up, any help is appreciated.
Convert(Date, TASK_START_DATE) <= Convert(Date, DateAdd(ww, -2, GetDate()))
Short version:
How do I correctly write a query that combines all records with the TASK_START_DATE OR TASK_END_DATE within two weeks in the future or past, i.e.
Select Task_ID, TASK_NAME, TASK_START_DATE, TASK_END_DATE
where
???
You can add days to your date for comparision:
Select * from Table
Where column between getdate()-14 and getdate()+14
You don't need to use "Convert" function. "GetDate" function returns datetime value and your columns' types are datetime. You can add day number directly like this:
Select * from Table
Where (TASK_START_DATE between getdate() - 14 and getdate() + 14)
or (TASK_FINISH_DATE between getdate() - 14 and getdate() + 14)
You can declare variables or have the comparison dates right in the where clause. I use GETDATE() to get the date/time for right now as it returns a DATETIME object. Then I use DATEADD to adjust it for days, months, years, etc, and then you have to convert it to a DATE before sticking it in a variable of type DATE. Note in the DATEADD method I pass in the adjustment type (D = days), then adjust it + or - 14 days.
Alternatively you could just use 14 days ago to the minute if you don't do the DATE conversions...you'd have to remove the converts from the variable declarations as well as the where clause. Depends on the results you want though.
DECLARE #twoWeeksAgo DATE = CONVERT(DATE, DATEADD(D, -14, GETDATE()));
DECLARE #twoWeeksAhead DATE = CONVERT(DATE, DATEADD(D, 14, GETDATE()));
SELECT
Task_ID,
TASK_NAME,
TASK_START_DATE,
TASK_END_DATE
FROM
TABLE
WHERE
CONVERT(DATE, TASK_START_DATE) BETWEEN #twoWeeksAgo AND #twoWeeksAhead
OR CONVERT(DATE, TASK_END_DATE) BETWEEN #twoWeeksAgo AND #twoWeeksAhead
Also note that the BETWEEN operator in the WHERE clause is inclusive, meaning it will include records where the TASK_START_DATE is equal to the dates held by the variables. If you wanted to exclude records with the same value as #twoWeeksAhead, for example, you would have to use something like
WHERE
(CONVERT(DATE, TASK_START_DATE) >= #twoWeeksAgo
AND CONVERT(DATE, TASK_START_DATE) < #twoWeeksAhead)
OR (CONVERT(DATE, TASK_END_DATE) >= #twoWeeksAgo
AND CONVERT(DATE, TASK_END_DATE) < #twoWeeksAhead)