我试图在@value变量中提取日期,如下所示。
Declare @value nvarchar(61)= 'Generated by radomemail@xyzdomain.com on 12/5/2014 1:00:13 PM from ATOM.'
Select SUBSTRING(@value,43,len(@value))
但问题是&#;; radomemail@xyzdomain.com'是变量,通过将起始指数从43
移位有没有更好的方法来做到这一点,我更喜欢一种方式,其中子串的起始位置将从@value的最后一个索引开始,并重新计算。
答案 0 :(得分:2)
Declare @value nvarchar(100)= 'Generated by radomemail@xyzdomain.com on 12/5/2014 1:00:13 PM from ATOM.'
Select LEFT(REVERSE(LEFT(REVERSE(RTRIM(@value)), 31)),20)
现在男孩和女孩,所有日期格式以及可变长度后缀的解决方案
Declare @values table (value nvarchar(100) NOT NULL);
INSERT @values VALUES
('Generated by radomemail@xyzdomain.com on 2/2/2014 1:00:13 PM from ATOM.'),
('Generated by radomemail@xyzdomain.com on 17/2/2014 1:00:13 PM from SOmewhere.'),
('Generated by radomemail@xyzdomain.com on 2/11/2014 1:00:13 PM from NeverNeverLand.'),
('Generated by radomemail@xyzdomain.com on 12/11/2014 1:00:13 PM from X.')
SELECT
RTRIM(SUBSTRING(V.value, PATINDEX(X.Pattern, V.value)+1, X.Patlength))
FROM
@values V
JOIN
(
VALUES
('% [1-9]/[1-9]/2[0-3][0-9][0-9]%', 20),
('% [1-3][0-9]/[1-9]/2[0-3][0-9][0-9]%', 21),
('% [1-9]/1[0-2]/2[0-3][0-9][0-9]%', 21),
('% [1-3][0-9]/1[0-2]/2[0-][0-9][0-9]%', 22)
) X (Pattern, Patlength) ON PATINDEX(X.Pattern, V.value) > 0
答案 1 :(得分:1)
使用CHARINDEX查找字符串on
,然后将其用作起点,然后执行相同操作以删除from
之后的文本:
Select SUBSTRING(@value,CHARINDEX(' on ', @value)+4,CHARINDEX(' from ', SUBSTRING(@value,CHARINDEX(' on ', @value)+4,len(@value))))