parse a column contains a path value in sql server

前端 未结 1 1271
既然无缘
既然无缘 2021-01-23 12:54

How I can parse a column that contains a URL path value in SQL Server?

The input

sites/System1/DocLib1/Folder1/SubFolder/File.pdf

shoul

相关标签:
1条回答
  • 2021-01-23 13:22

    If you have a known or max number of levels, you can use a little XML.

    If unknown, you would have to go dynamic.

    Example

    Declare @yourtable table (id int,url varchar(500))
    Insert Into @yourtable values
    (1,'sites/System1/DocLib1/Folder1/SubFolder/File.pdf')
    
    Select A.id
          ,B.*
     From  @yourtable A
     Cross Apply (
                    Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                          ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                          ,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
                          ,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
                          ,Pos5 = ltrim(rtrim(xDim.value('/x[5]','varchar(max)')))
                          ,Pos6 = ltrim(rtrim(xDim.value('/x[6]','varchar(max)')))
                          ,Pos7 = ltrim(rtrim(xDim.value('/x[7]','varchar(max)')))
                          ,Pos8 = ltrim(rtrim(xDim.value('/x[8]','varchar(max)')))
                          ,Pos9 = ltrim(rtrim(xDim.value('/x[9]','varchar(max)')))
                    From  (Select Cast('<x>' + replace(url,'/','</x><x>')+'</x>' as xml) as xDim) as A 
                 ) B
    

    Returns

    id  Pos1    Pos2    Pos3    Pos4    Pos5        Pos6        Pos7    Pos8    Pos9
    1   sites   System1 DocLib1 Folder1 SubFolder   File.pdf    NULL    NULL    NULL
    
    0 讨论(0)
提交回复
热议问题