首页 > 解决方案 > SQL Server CHARINDEX 函数

问题描述

我正在寻找一些用 for 循环或其他方式替换列中所有行的函数。该函数需要通过反向给出特定字符的子字符串(从末尾开始的第三个反斜杠)

前 :'חוזה - דף ראשון#Y:\Access\Shiduhim\Agreem1\999999.Bmp'

需要在方法之后:'Shiduhim\Agreem1\999999.Bmp'

标签: sqlsql-servertsql

解决方案


您的问题可以通过递归 CTE解决(需要了解maxrecursion):

declare @t table(
  path nvarchar(260)
);

insert into @t(path) values
  (N'חוזה - דף ראשון#Y:\Access\Shiduhim\Agreem1\999999.Bmp'),
  ('C:\abc\defg\hi.png'),
  ('17042.jpg'),
  ('D:\foo\bar.tiff');

declare @n int = 3;

with
  r as (
    select r, 0 as p, 0 as n, iif(charindex('\', r) > 0, 1, 0) as x
    from @t
    cross apply (select reverse(path)) as a(r)
    union all
    select r, a.p, n + 1, iif(n < @n - 1 and charindex('\', r, a.p + 1) > 0, 1, 0)
    from r
    cross apply (select charindex('\', r, p + 1)) as a(p)
    where x = 1
  )
select
  reverse(iif(n < @n, r, left(r, p - 1))) as path
from r
where x = 0;

输出:

+-----------------------------+
|            path             |
+-----------------------------+
| 17042.jpg                   |
| D:\foo\bar.tiff             |
| abc\defg\hi.png             |
| Shiduhim\Agreem1\999999.Bmp |
+-----------------------------+

演示


推荐阅读