Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PATINDEX在SQL Server中使用多种格式查找文本中的时间_Sql_Sql Server_Sql Like_Patindex - Fatal编程技术网

使用PATINDEX在SQL Server中使用多种格式查找文本中的时间

使用PATINDEX在SQL Server中使用多种格式查找文本中的时间,sql,sql-server,sql-like,patindex,Sql,Sql Server,Sql Like,Patindex,我需要使用一个正则表达式,它返回12:43和1:33格式的时间,我尝试了以下方法,每个方法都返回所需的结果,我如何将两者结合起来,以便SQL可以返回第一个或第二个结果: set @reg = '[0-9]:[0-5][0-9]' set @reg = '[0-1][0-2]:[0-5][0-9]' 我所尝试的: Declare @reg nvarchar(100) set @reg = '[0-9]:[0-5][0-9]' --set @reg = '[0-1][0-2]:[0-5][0-

我需要使用一个正则表达式,它返回12:43和1:33格式的时间,我尝试了以下方法,每个方法都返回所需的结果,我如何将两者结合起来,以便SQL可以返回第一个或第二个结果:

set @reg = '[0-9]:[0-5][0-9]'
set @reg = '[0-1][0-2]:[0-5][0-9]'
我所尝试的:

Declare @reg nvarchar(100) 
set @reg = '[0-9]:[0-5][0-9]' 
--set @reg = '[0-1][0-2]:[0-5][0-9]' 

select remarks, 
       substring(remarks,PATINDEX('%' + @reg + '%',remarks) ,5), len(PATINDEX('%' + @reg + '%',remarks)) 
from infraction 
where remarks like '%' + @reg + '%'

您需要找到任何一个模式存在的行,然后根据模式匹配的行应用适当的SQL受限“regex”。
HH:MM
one比
H:MM
更具限制性,因此我们使用它来检查

CREATE TABLE #infraction (
  Comment VARCHAR(100)
)

INSERT INTO #infraction VALUES ('time of 12:35 incident')
INSERT INTO #infraction VALUES ('time of 1:34 incident');

DECLARE @reg NVARCHAR(100) = '[0-9]:[0-5][0-9]'
DECLARE @reg2 NVARCHAR(100) = '[0-1][0-2]:[0-5][0-9]'

SELECT
    Comment,
    IIF(PATINDEX('%' + @reg2 + '%', Comment) = 0,
        SUBSTRING(Comment, PATINDEX('%' + @reg + '%', Comment), 4),
        SUBSTRING(Comment, PATINDEX('%' + @reg2 + '%', Comment), 5)
    )
FROM
    #infraction 
WHERE
    Comment LIKE '%' + @reg + '%'
    or
    Comment LIKE '%' + @reg2 + '%';
返回:

12:35
1:34

正如您可能看到的,我需要从表中保存的文本字段中提取时间,如何仅返回提取的时间请发布您现在使用的整个查询。