簡體   English   中英

當列在 sql 中具有 null 值時,將日期列從 varchar 轉換為日期類型

[英]Convert date column from varchar to date type when column has null values in sql

表 df 用 col 表示日期。 Date_col 是varchar類型

Date_col
1/30/2010
10/7/2020
NULL 
2/28/2017   and so on

試過了

alter table df
alter column Date_col date

錯誤:

Conversion failed when converting date and/or time from character string.

試圖將 Date_col 列轉換為日期類型。 Date_col 列中還有 null 值。 如何將列類型從 varchar 轉換為date

將字符串轉換為日期的正確格式是101 ( mm/dd/yyyy )。

所以首先嘗試使用SELECT語句進行轉換:

select convert(date, Date_col, 101) Date_col from df

如果您收到任何錯誤,則日期字符串不是正確的日期。
如果沒有問題,則更新表:

update df
set Date_col = convert(date, Date_col, 101)

並更改列的數據類型:

alter table df
alter column Date_col date

請參閱演示

先更新值,再改變類型:

update df
    set date_col = try_convert(date, date_col, 101);

alter table df alter column Date_col date;

我建議您在update之前檢查新值:

select date_col
from df
where try_convert(date, date_col, 103) is null and date_col is not null;

您可以找出列中是否有需要注意的異常值。

因為 sql 服務器中的默認日期格式是 ymd,所以:

SET DATEFORMAT dmy

alter table df
alter column Date_col date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM