首页 > 解决方案 > 当列在sql中具有空值时,将日期列从varchar转换为日期类型

问题描述

表 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 列中也有空值。如何将列类型转换date为 varchar。

标签: sqlsql-server

解决方案


将字符串转换为日期的正确格式是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

请参阅演示


推荐阅读