我的SQL Server表中有一个包含文件路径(包含文件夹和子文件夹)的列
例如:
/Hidden Reporting/Validation Report
/Top Reporting/Inner/TopTools Report
我目前有一个查询返回这些路径的所有主文件夹:
Select Distinct
LEFT((substring(Path, 2, (LEN(Path) - 1))), CHARINDEX('/', (substring(Path, 2,(LEN(Path) - 1)))) - 1) AS Folder
FROM dbo.Catalogs
Where Type=2
结果:
Hidden Reporting
Top Reporting
但我也需要获得子文件夹。
例如:
Hidden Reporting
Top Reporting
Inner
如何在SQL Server 2008中执行此操作?
答案 0 :(得分:2)
首先创建一个表值函数来分割字符串。我得到了以下功能,从其他地方拆分
create FUNCTION [dbo].[SplitString]
(
@sString varchar(5000),
@cDelimiter char(1)
)
RETURNS @tParts TABLE ( part varchar(5000) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter
begin
set @iStart = 2
insert into @tParts
values( null )
end
else
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos - @iStart > 0
insert into @tParts
values ( substring( @sString, @iStart, @iPos-@iStart ))
else
insert into @tParts
values( null )
set @iStart = @iPos+1
if @iStart > len( @sString )
break
end
RETURN
END
现在您可以执行下面的选择查询以获得所需的输出
SELECT part
FROM Catalogs C
cross APPLY dbo.SplitString( substring([Path],1,LEN([Path]) -
CHARINDEX('/',REVERSE([Path]))) ,'/') AS Results
WHERE ISNULL(part,'') <> ''