1

我的 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 中执行此操作?

4

1 回答 1

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,'') <> ''  
于 2012-07-13T10:41:43.033 回答