SQL Server: áp dụng regex thay thế

Nov 09 2020

Đây là truy vấn SQL của tôi:

select codi_nivell 
from anc_documents

Dữ liệu ví dụ là:

06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000
06080100000000

Tôi cần áp dụng regex này cho truy vấn SQL của mình:

Đầu tiên, tôi cần theo dõi từ xa 0.

Sau đó, áp dụng regex này để thêm /mỗi hai chữ số:

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

Có ý kiến ​​gì không?

Trả lời

GordonLinoff Nov 09 2020 at 11:57

SQL Server không hỗ trợ biểu thức chính quy. Nhưng bạn có thể làm điều này bằng cách sử dụng một số thao tác chuỗi và CTE đệ quy:

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;

Đây là một db <> fiddle.

Tyron78 Nov 09 2020 at 12:29

Bạn có thể đạt được điều này bằng cách sử dụng XML PATH:

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