2017-04-10 109 views
0

您能否幫助我在下面的文本中的原因代碼之後提取日期和文本?我可以使用patindex日期,但問題是我的日期可以DD/MM/YYYY或d/M/YYYYSQL Server字符串解析

項目推遲到2017年3月2日與原因代碼:客戶關係,客戶將無法使用

項目重新計劃到2/3/2017,原因碼:天氣惡劣

我沒有創建函數的權限,它必須是SQL查詢。

感謝, 阿努

回答

-1

在SQL,你不能提取存在於同一列作爲信息數據。因此,如果信息退出同一列,則無法提取。因此,信息必須放在不同的表格中以便提取。

0

您可能應該爲輸入文本添加驗證以包含'with'和'to'或過濾'invalid'條目。但是,這基本上是你問的:

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) 
0
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