sql - 当列在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。
解决方案
将字符串转换为日期的正确格式是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
请参阅演示。
推荐阅读
- html - CSS 按钮未正确对齐
- php - 按键的值对 ArrayObject 进行排序
- r - 一列中的唯一单词总数 - R
- frontend - 为什么在注册表单上使用前端验证而不在登录表单上使用?
- ffmpeg - 使用 Node.js 模块 fluent-ffmpeg 输入要连接的文件列表
- geolocation - 提高 GPS 精度
- javascript - Angular5 的 Canvas JS 问题
- angular - 在角度 4 中获取问题可选参数郊游问题?
- xamarin.forms - Android 上 DependencyService 的 NullReferenceException
- python - Django REST框架教程1中的ImportError:序列化