繁体   English   中英

从字符串中提取日期并插入到字段Microsoft SQL Server 2012中

[英]Extract date from string and insert into field Microsoft SQL Server 2012

假设我有一个字段UserAddedInfo,其字符串“用户已添加到系统并在2016年5月16日由User Annon从列表中删除”,并在同一个表中添加了字段DateAdded。

SQL中是否有任何方法从字符串字段中提取16/05/2016日期并将其作为日期时间插入DateAdded字段?

字符串中的日期始终为dd / MM / yyyy。

谢谢!

使用PATINDEX获取列中日期字符串的起始位置,并从该位置提取10个字符。 要将提取的字符串转换为date ,请使用格式为103 CONVERT

103 = dd / mm / yyyy

select 
convert(date,
substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10)
      ,103)
from table_name
where patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo) > 0

要更新表中的dateadded字段,请使用

update table_name
set dateadded = convert(date,
substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10)
      ,103)
where patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo) > 0

当子字符串返回无效日期时,使用try_casttry_convert返回null

select 
try_cast(
substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10) 
as date) 
--or
--try_convert(date,
--substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10) 
--) 
from table_name
where patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo) > 0

您可以使用patindex查找日期字符串,并使用强制转换将其转换为日期时间

select 
    cast(substring('User was added to the system and removed from list on 27/08/2014 by User Annon', 
        patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%', 
                 'User was added to the system and removed from list on 27/08/2014 by User Annon'), 10) as datetime)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM