这是我的问题:
我从这样的列中得到了一个字符串:
**0756FJ89045GJD38**.pdf
现在我必须通过这个字符串生成一个路径:
/home/ars/07/56/FJ/89/04/5G/JD/38/0756FJ89045GJD38.pdf
我必须使用两个字符并将其从左到右构建到一个路径级别。
也许你可以帮助我,谢谢!
答案 0 :(得分:2)
这可能有所帮助:
DECLARE @p nvarchar(100) = '**0756FJ89045GJD38**.pdf',
@n int = 3
;WITH cte AS (
SELECT STUFF(REPLACE(SUBSTRING(@p,1,CHARINDEX('.',@p)-1),'*',''),1,0,'/') as p, 1 [level]
UNION ALL
SELECT STUFF(p,[level]+@n,0,'/'), [level]+@n
FROM CTE
WHERE LEN(STUFF(p,[level]+@n,0,'/')) >= [level]+@n
)
SELECT TOP 1 @p = '/home/ars'+p +'/'+REPLACE(@p,'*','')
FROM cte
ORDER BY [level] DESC
SELECT @p
输出:
/home/ars/07/56/FJ/89/04/5G/JD/38/0756FJ89045GJD38.pdf
修改强>
如果有一个包含PDF文件名的表并且所有名称大小相同,那么您可以这样做:
DECLARE @n int = 3
;WITH pdf AS (
SELECT *
FROM (VALUES
('**0756FJ89045GJD38**.pdf'),
('**1729DA8CD189700A**.pdf'),
('**A6710936BCD47832**.pdf'),
('**00A764D617B93978**.pdf')
) as t(file_)
)
,cte AS (
SELECT file_, STUFF(REPLACE(SUBSTRING(file_,1,CHARINDEX('.',file_)-1),'*',''),1,0,'/') as p, 1 [level]
FROM pdf
UNION ALL
SELECT file_, STUFF(p,[level]+@n,0,'/'), [level]+@n
FROM CTE
WHERE LEN(STUFF(p,[level]+@n,0,'/')) >= [level]+@n
)
SELECT TOP 1 WITH TIES '/home/ars'+p +'/' + REPLACE(c.file_,'**','')
FROM cte c
ORDER BY ROW_NUMBER() OVER (PARTITION BY file_ ORDER BY [level]) DESC
输出:
/home/ars/00/A7/64/D6/17/B9/39/78/00A764D617B93978.pdf
/home/ars/A6/71/09/36/BC/D4/78/32/A6710936BCD47832.pdf
/home/ars/17/29/DA/8C/D1/89/70/0A/1729DA8CD189700A.pdf
/home/ars/07/56/FJ/89/04/5G/JD/38/0756FJ89045GJD38.pdf