Convert text to date format - sql

How do I convert a text format e.g.
Thursday, 1 January 2009
to a date in sql?
Thank you

For SQL Server you can use:
SELECT CAST(
SUBSTRING('Thursday, 1 January 2009',
CHARINDEX(',', 'Thursday, 1 January 2009')+1, LEN('Thursday, 1 January 2009'))
AS DATETIME)

What type of text do you mean?
if you mean any type of text .... that isn't exist
if you mean text like '19900101' or like '1/1/2005' ... this will be converted to date automatic in sql server

Related

Convert character string into this specific date format?

I am using SQL Server 2014 and I have a table (t1) which contain a column (ReviewDate) in the nvarchar format.
An example of a row of this column is given below:
ReviewDate
Mr John wrote a review in Oct 2017
I need to extract the "date" component from this character string.
To do this, my T-SQL is as follows:
SELECT (RIGHT([ReviewDate], 8)) as [ReviewDate 2]
FROM t1
This gives me "Oct 2017".
Now, I want to convert the "Oct 2017" into "2017-10-01" as a datetime format. This is where I am stuck.
I have tried the following:
SELECT CONVERT(datetime, (RIGHT([ReviewDate], 8)), 121) as [ReviewDate2]
Above syntax gives me the following error message: "Conversion failed when converting date and/or time from character string."
SELECT CAST( (RIGHT([ReviewDate], 8)) as datetime) as [ReviewDate2]
Above syntax gives me the same error message:
Conversion failed when converting date and/or time from character string.
Some help will be appreciated.
All your queries are right but make sure that, it should not have any other string apart from date part.
For example SELECT CAST('x Oct 2017' AS DATE) will give you error like
Conversion failed when converting date and/or time from character
string.
SELECT CAST((RIGHT('Mr John wrote a review in Oct 2017', 8)) as datetime) as [ReviewDate2]
SELECT CAST('Oct 2017' AS DATE)
SELECT CONVERT(DATETIME, 'Oct 2017 ', 121) as [ReviewDate2]
FIDDLE DEMO
so far your sample text is a valid datetime in mssql when I tried to cast. It seems there's some invalid data on your table. try using try_cast() to include those invalid data.
declare #ReviewDate varchar(max)='Mr John wrote a review in Oct 2017'
set #ReviewDate = (RIGHT(#ReviewDate, 8))
select try_cast(#ReviewDate as datetime) as [ReviewDate2]
dbfiddle<>

Failed conversion from nvarchar to datetime

I am trying to convert an nvarchar date into a date time, but this error occurs: I have tried multiple ways including CAST and Convert (as code below) with no avail. Any suggestions ?
Date Format : Wed, 19 Jul 2017 16:23:38 +0000
Code:
INSERT INTO feed.article(title,link,sourceID,[date])
SELECT title,link,s.sourceID,
CONVERT(DATETIME,[date],121)
FROM feed.tempXML t
JOIN feed.[source] s ON s.sourceName = t.[source]
Error given:
Conversion failed when converting date and/or time from character string.
If you have MS SQL Server 2012 or higher, you may use TRY_PARSE.
SELECT CAST(TRY_PARSE ('Wed, 19 Jul 2017 16:23:38 +0000' AS datetimeoffset) AS datetime)
I would do this in two parts, one for the date and one for the time:
SELECT title,link,s.sourceID,
(CONVERT(DATETIME, SUBSTRING([date], 5, 10), 106) +
CONVERT(DATETIME, SUBSTRING([date], 18, 8))
)
FROM feed.tempXML t JOIN
feed.[source] s
ON s.sourceName = t.[source];
This minimizes the string operations, so it seems like a pretty simple approach.
EDIT: Check out the solutions by Oleg and Gordon. I actually prefer them both to my own (as it's quite convoluted).
You need to get your date format from this...
'Wed, 19 Jul 2017 16:23:38 +0000'
...to this...
'19 Jul 2017 16:23:38'
You can remove chars from the beginning and end using LEFT and RIGHT. Removing the last 6 from the end would look like this:
LEFT([date], LEN[date] - 6)
We can use the same syntax for our RIGHT() to remove the first 5, but [date] must now be replaced with the entire string from above:
-- RIGHT([date], LEN([date]) - 5) becomes...
RIGHT(LEFT(#d, LEN(#d) - 6), LEN(LEFT(#d, LEN(#d) - 6)) - 5)
All in all, it's ugly, but works:
INSERT INTO feed.article(title,link,sourceID,[date])
SELECT title,link,s.sourceID,
CONVERT(DATETIME,RIGHT(LEFT([date], LEN([date]) - 6), LEN(LEFT([date], LEN([date]) - 6)) - 5),121)
FROM feed.tempXML t
JOIN feed.[source] s ON s.sourceName = t.[source]
IMPORTANT NOTE: This is under the assumption that the format of your date will always have 5 unnecessary characters at the beginning, and that your timezone offset (the +0000 at the end) will always be 0 (so we can simply ignore it).
If you'll have values that make use of the timezone offset, you'll need to account for that.
Based on the format, we should be able make a few "safe assumptions"...
1) The weekday will always be expressed as a 3 char abbreviation.
2) The 3 char abbreviation will be followed by a comma and a space.
3) The portion of code we're interested in will be either 19 or 20 characters.
(10 for single digit dates and 20 for double digit dates)
4) There will be a space following the date.
Based on these assumptions, you should be safe to use the following...
CREATE TABLE #TestData (
StringDate NVARCHAR(40) NOT NULL
);
INSERT #TestData (StringDate) VALUES
(N'Wed, 19 Jul 2017 16:23:38 +0000'),
(N'Wed, 9 Jul 2017 16:23:38 +0000');
SELECT
DateTimeDate = CAST(SUBSTRING(td.StringDate, 6, 20) AS DATETIME)
FROM
#TestData td;

How to check if column having date of birth format has yyyymmdd in sql server?

How to check if column having date of birth format has yyyymmdd in sql server?
You can verify with the ISDATE Function, but I don't know which SQL edition do you have
Example
select ISDATE ( 1 )
------------------
0
select ISDATE ( 11111111 )
------------------
0
select ISDATE ( 20170501)
------------------
1
You can use:
select (case when try_convert(date, dob) is not null and
try_convert(int, dob) is not null
then 1 else 0
end)
I'm not 100% sure, but I think that yyyymmdd is the only format that will generally pass both conditions. Note: There is no way to know if 20170601 is really June 1st or Jan 6th, so this cannot actually validate the contents of the field.
But why do you care what the format is, so long as you can convert it to a date? You should then change the column to a date type and henceforth know that the "format" is correct.
If the column is a Char type (yuck) then Like '[12][0-9][0-9][0-9][0-1][0-9][0-3][0-9]' (off the top of my head)
If it's a DateTime then who cares, it's a date.

How do I convert date like '31/06/2013' or '30/02/2013' of datatype varchar in SQL Server 2008

I have a column named next_due_date datatype varchar and in this column some non-existing dates like 31/06/2012 or 30/02/2013 are saved. Because of this I get an error message when I convert it to date datatype.
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
If you dates would be valid (not something like the 31st of June or 30th of February - those dates simply don't exist!), then you could easily use the CONVERT function to convert them to DATE:
DECLARE #DateTable TABLE (DateColumn VARCHAR(20))
-- **VALID** dates - 30th of June, 28th of Feb
INSERT INTO #DateTable(DateColumn) VALUES ('30/06/2012'), ('28/02/2013')
-- easily converted to DATE type using style #104
SELECT DateColumn, CONVERT(DATE, DateColumn, 104)
FROM #DateTable
You can use try_parse (which is only available on higher SQL version, from 2012 on wards). It checks if a date is valid. If so, it returns the date, else null.
I think en-GB is the culture you need:
select try_parse('30/06/2012' as date using 'en-GB') -- returns a valid date
select try_parse('31/06/2012' as date using 'en-GB') -- returns null
If you need this on lower platforms, I would suggest to parse it by hand using a procedure. Something like this:
BEGIN TRY
select CONVERT(date,'31/06/2012',103)
END TRY
BEGIN CATCH
select null
END CATCH

Convert date of format dd mon yyyy to return integer of month in SQL

I have a varchar variable containing value 01 May 2013 and I need to obtain the integer of the Month part.
for eg if 01 May 2013 is input I should get the result as 5
The query I wrote was :
select DATEPART(MM,CONVERT(DATETIME,CONVERT(VARCHAR(15),'01 '+SUBSTRING(FISCAL_MONTH,1,3)+' 2013'),100))
FROM <table name>
Here FISCAL_MONTH is my column name from the table. However this query is showing me the result, for eg 11 for November but is also throwing the following error :
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have tried various combinations, bit in vain. Kindly note I need it in a query. Kindly help.
If that is the only date you want to convert then you can simplify the SQL statement to:
select datepart(mm,convert(datetime,'01 May 2013'))
I just used this to test and it worked:
declare #t as varchar(333)
set #t = '01 May 2013'
select datepart(mm,convert(datetime, #t))
Gives me
5
If you are still getting that conversion error, then you either have some NULL values OR some date values that are not in the correct format. Check the data in your table to see which it is.
I'll leave it to you to add the rest of the months.
select case substring('01 MAY 2013',4,3) when 'JAN' then 1
when 'FEB' then 2
when 'MAR' then 3
when 'APR' then 4
when 'MAY' then 5
when 'JUN' then 6 else 9999 end
It might just be that there is a 3 instead of a 2 in the substring argument:
SUBSTRING(FISCAL_MONTH,1,2)+' 2013'),100))
The concat might work also:
select DATEPART(MM, CONCAT('01/', substring(convert(varchar(15),'03/23/2013'),1,2),'/2013'));
Wow, it is real interesting to see all the weird code that people come up with. I use the KISS policy most of the time (keep it simple stupid).
How about the MONTH() function. It has been in the TSQL language forever. I even threw in a coalesce to handle any unexpected NULLS.
-- Simple date as text
declare #var_test varchar(20) = '01 may 2013';
-- Use coalesce to handle nulls, use month to return int
select month(coalesce(#var_test, '01 jan 1900')) as my_month_index
Select month ( cast ( date_col as datetime ))
From table
You have to convert with proper format, you have to pass the apprpriate format-style value on your conversion. As per MSDN, you are using "dd mon yy" format, so you have to supply the corresponding format-style-code 6 or 106
Declare #FISCAL_MONTH nvarchar(max) = '01 May 2013'
select datepart(mm,Convert(datetime, #FISCAL_MONTH, 6))
--5
Set #FISCAL_MONTH = '01 November 2013'
select datepart(mm,Convert(datetime, #FISCAL_MONTH, 6))
--11