[英]Extract date from string and insert into field Microsoft SQL Server 2012
Say I have a field UserAddedInfo with a string "User was added to the system and removed from list on 16/05/2016 by User Annon" and a field DateAdded in the same table. 假设我有一个字段UserAddedInfo,其字符串“用户已添加到系统并在2016年5月16日由User Annon从列表中删除”,并在同一个表中添加了字段DateAdded。
Is there any way in SQL to extract that 16/05/2016 date from the string field and insert it into the DateAdded field as a datetime? SQL中是否有任何方法从字符串字段中提取16/05/2016日期并将其作为日期时间插入DateAdded字段?
The date in the string is always going to be dd/MM/yyyy. 字符串中的日期始终为dd / MM / yyyy。
Thanks! 谢谢!
Use PATINDEX
to get the start position of the date string in the column and extract 10 characters from that position. 使用
PATINDEX
获取列中日期字符串的起始位置,并从该位置提取10个字符。 To convert the extracted string to date
, use CONVERT
with format 103
. 要将提取的字符串转换为
date
,请使用格式为103
CONVERT
。
103 = dd/mm/yyyy
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
To update the dateadded field in the table, use 要更新表中的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
Use try_cast
or try_convert
to return null
when the substring returns invalid dates. 当子字符串返回无效日期时,使用
try_cast
或try_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
You can use patindex to find date string, and use cast to convert it to datetime 您可以使用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.