Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.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
SQL Server:应用带有替换项的正则表达式_Sql_Sql Server_String - Fatal编程技术网

SQL Server:应用带有替换项的正则表达式

SQL Server:应用带有替换项的正则表达式,sql,sql-server,string,Sql,Sql Server,String,以下是我的SQL查询: select codi_nivell from anc_documents 示例数据为: 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 06080100000000 我需要将此正则表达式

以下是我的SQL查询:

select codi_nivell 
from anc_documents
示例数据为:

06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
我需要将此正则表达式应用于我的SQL查询:

select codi_nivell 
from anc_documents
首先,我需要远程跟踪0

然后应用此正则表达式,以便每两位数添加一个/或:

regex: \d{2}(?=(?:\d{2})+$)
replace: $0/

有什么想法吗?

SQL Server不支持正则表达式。但您可以使用一些字符串操作和递归CTE来实现这一点:

with ad as (
      select row_number() over (order by code) as seqnum, replace(rtrim(replace(code, '0', ' ')), ' ', '0') as new_code
      from anc_documents
     ),
     cte as (
      select seqnum, new_code, 0 as offset, 0 as lev
      from ad
      union all
      select seqnum, stuff(new_code, offset + 3, 0, '-'), offset + 3, lev + 1
      from cte
      where offset + 3 < len(new_code) 
     )
select *
from (select max(lev) over (partition by seqnum) as max_lev, cte.*
      from cte
     ) cte
where max_lev = lev;

是一个dbfiddle。

您可以通过使用XML路径来实现这一点:

DECLARE @codi_nivell NVARCHAR(100) = (SELECT REVERSE(CAST(REVERSE('06080100000000') AS BIGINT)))

;WITH cte AS(
 SELECT @codi_nivell AS codi_nivell, LEFT(@codi_nivell, 2) AS codi_nivell_left, RIGHT(@codi_nivell, LEN(@codi_nivell)-2) AS codi_nivell_right
 UNION ALL
 SELECT @codi_nivell, LEFT(codi_nivell_right, 2), RIGHT(codi_nivell_right, LEN(codi_nivell_right)-2)
   FROM cte
   WHERE LEN(codi_nivell_right) >= 2
)
SELECT STUFF((SELECT '/' + c2.codi_nivell_left
  FROM cte c2
  FOR XML PATH('')), 1, 1, '') y
  FROM cte c1
  GROUP BY c1.codi_nivell

SQL Server不支持正则表达式-因此,与其向我们显示正则表达式,不如向我们显示所需的结果。另外,在进行此操作时,请向我们展示您当前的尝试。如果您确实需要SQL Server中的true Regex支持,则需要实现CLR函数。您的所有字符串的格式是否与问题中显示的格式相同?