你能帮我提取以下文本中原因代码之后的日期和文本吗?我可以将patindex
用于日期,但问题是我的日期可以是日/月/年或 d/m/yyyy
项目重新安排到 03/02/2017,原因代码:客户相关客户将不可用
项目改期至2017年2月3日,原因代码:天气恶劣
我没有创建函数的权限,它必须是SQL查询。
谢谢安努
您可能应该为输入文本添加验证以同时包含"with"和"to"或过滤掉"无效"条目。但这基本上是你所要求的:
declare @s varchar(255)
set @s = 'Project rescheduled to 2/3/2017 with reason code : Weather Inclement'
select RIGHT(LEFT(@s, CHARINDEX(' with', @s)-1), CHARINDEX(' with', @s) -CHARINDEX('to', @s) - 3)
Declare @YourTable table (ID int,SomeCol varchar(500))
Insert Into @YourTable values
(1,'Project rescheduled to 03/02/2017 with reason code : Customer Related-Customer Will Not Be Available'),
(2,'Project rescheduled to 2/3/2017 with reason code : Weather Inclement')
Select A.ID
,Date = try_convert(date,right(B.dP,len(B.dp)-charindex(' ',B.dP)),103)
,Reason = right(SomeCol,len(SomeCol)-charindex(':',SomeCol)-1)
From @YourTable A
Cross Apply (
Select dP=substring(A.SomeCol,patindex('%/[0-9][0-9][0-9][0-9]%',A.SomeCol)-6,11)
) B
返回
ID Date Reason
1 2017-02-03 Customer Related-Customer Will Not Be Available
2 2017-03-02 Weather Inclement
在 SQL 中,不能提取与信息位于同一列中的数据。因此,如果信息在同一列中退出,则无法提取。因此,信息必须位于不同的表中才能提取。