I have a column that is a date column that is stored as text. This has three formats in it.
I need to convert all these to one format. Im hoping 112 (yyyymmdd)
can anyone help as I keep getting an out of range error.
I have got it to return this correctly
CONVERT(varchar(10), ISNULL(CAST(cf3.FieldValue as date),CAST('01/01/1900' as date)),101)
But I cant seem to then convert to yyyymmdd format without the range error.
Input:
01 Jan 1900
12/5/2013
2013-12-10
Query:
SELECT CONVERT(VARCHAR, CONVERT(DATE, TestColumn), 112)
FROM tblTestTable
Output:
19000101
20131205
20131210
Using SQL Server 2008 R2
You can use combination of STR_TO_DATE
with DATE_FORMAT
to achieve desired results.
SELECT
IFNULL(
DATE_FORMAT(STR_TO_DATE(COL_NAME, '%d %b %Y'), '%Y%m%d'),
IFNULL(
DATE_FORMAT(STR_TO_DATE(COL_NAME, '%d-%m-%Y'), '%Y%m%d'),
DATE_FORMAT(STR_TO_DATE(COL_NAME, '%Y-%m-%d'), '%Y%m%d')
)
) FROM TABLE_NAME;
STR_TO_DATE
will convert the string into a datetime datatype and then DATE_FORMAT
will convert datetime into the desired format( '%Y%m%d'
-> 'yyyymmdd'
).
declare @mydate datetime = '2017-03-20'
select RIGHT('0' + CAST(DATEPART(DD,@mydate) as nvarchar(max)),2) + ' ' + UPPER(CAST(DATENAME(month,@mydate) AS VARCHAR(3))) + ' ' + CAST(DATEPART(YEAR, @mydate) as nvarchar(MAX)) as 'dd mmm yyyy',
RIGHT('0' + CAST(DATEPART(DD,@mydate) as nvarchar(max)),2) + '/' + RIGHT('0' + CAST(DATEPART(MONTH, @mydate) as nvarchar(Max)),2) + '/' + CAST(DATEPART(YEAR, @mydate) as nvarchar(MAX)) as 'dd/mm/yyyy',
CAST(DATEPART(YYYY,@mydate) as nvarchar(max)) + '-' + RIGHT('0' + CAST(DATEPART(MONTH, @mydate) as nvarchar(Max)),2) + '-' + RIGHT('0' + CAST(DATEPART(DD, @mydate) as nvarchar(MAX)),2) as 'yyyy-mm-dd'
You can manually get the corresponding dateparts of the date and perform the formatting yourself. (if format needed is not readily available)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.