[英]Convert multiple date formats stored as text
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)
我希望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. 但是我似乎无法然后将其转换为yyyymmdd格式而没有范围错误。
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 使用SQL Server 2008 R2
You can use combination of STR_TO_DATE
with DATE_FORMAT
to achieve desired results. 您可以将
STR_TO_DATE
与DATE_FORMAT
结合使用以获得所需的结果。
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'
). STR_TO_DATE
将字符串转换为日期时间数据类型,然后DATE_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)
(如果所需格式不容易获得)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.