[英]SQL Server - How to convert varchar to date
我有一個包含StartDate的表,格式為dd / mm / yyyy和yyyy-mm-dd。 我想將此varchar列轉換為DD / MM / YYYY格式的DATE類型。
我已經嘗試了以下。
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
和
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
我從字符串轉換日期和/或時間時收到錯誤-轉換失敗。
請建議。
對於沒有格式參數的日期轉換,SQL Server實際上非常有用。 但是,它將假定MM/DD/YYYY
為第二種格式,並產生錯誤。
因此,您可以使用try_convert()
和coalesce()
:
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
這是一個SQL Fiddle。
然后,您應該進入數據並修復該列。 這是一種方法:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
您可以使用convert()
日期改回字符串,從而為結果集添加其他格式。
要獲取YYYY-MM-DD,請使用SELECT CONVERT(varchar, getdate(), 23)
要獲取MM / DD / YYYY,請使用SELECT CONVERT(varchar, getdate(), 1)
有關詳細說明,請嘗試此 。
如果您只有日期字符串為dd / mm / yyyy或yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
這是一個示例,首先嘗試將VARCHAR從“ yyyy-mm-dd”格式轉換為“ dd / mm / yyyy”格式。
如果仍無法解決問題,則僅假設它已經是“ dd / mm / yyyy”格式。
然后默認為字符串中的前10個字符。
declare @TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into @TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from @TestTable t;
但是try_convert僅在MS SQL Server 2012之后可用。
對於MS SQL Server 2008,我們可以使用CASE WHEN和LIKE來檢查格式。
declare @TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into @TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from @TestTable t;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.