2016-09-07 30 views
0

我有一些數據在一個巨大的表看起來像這樣:如何使用SQL找到父directoryId

directoryId Length Directory 
7788 631  Y:\Foo 
3606 70246 Y:\Foo\Bar 

如何使用SQL尋父文件夾,並提供父ID?

DirID  ParentDirId Length   Directory 
3606   7788   70246   Y:\Foo\Bar 

源表:

CREATE TABLE [Datamap].[SourceFiles](
    [DirectoryID] int IDENTITY(1,1), 
    [Length] [float] NULL, 
    [Directory] [nvarchar](255) NULL, 
    [Extension] [nvarchar](255) NULL, 
    [Type] [nvarchar](max) NULL 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

GO 

我只有在每排direcotry ID。

所以我編輯了這個和我的解決方案。我創建了一個如上所示的表格,它包含這樣的數據:

directoryId Length Directory Extension Type 
23572 2270 Y:\Data\FS02-V\HarvardPilgrim\Development\Dory\FHCP ICD10 sql Sql Scripts 
23572 4396 Y:\Data\FS02-V\HarvardPilgrim\Development\Dory\FHCP ICD10 sql Sql Scripts 
23572 1420 Y:\Data\FS02-V\HarvardPilgrim\Development\Dory\FHCP ICD10 sql Sql Scripts 
+0

你知道你正在搜索的ID,什麼是表名? – Stivan

+0

http://social.technet.microsoft.com/wiki/contents/articles/17948.t-sql-right-left-substring-and-charindex-functions.aspx – Missy

+0

我提供我的表看起來像@Stivan什麼,但我只有一個目錄ID。我現在想提供一個家長ID。我確定我可以從目錄字段中刪除它,但我想知道如何將它提供回該行。 – VinnyGuitara

回答

1

以下是一種可能的解決方案。

Declare @YourTable table (directoryId int,Length int, Directory varchar(250)) 
Insert into @YourTable values 
(7788,631,'Y:\Foo'), 
(3606,70246,'Y:\Foo\Bar'), 
(3607,70246,'Y:\Foo\Bar\SomeDir & Date') 



;with cteBase as (
Select A.* 
     ,B.* 
From @YourTable A 
Cross Apply (Select Top 1 * from [dbo].[udf-Str-Parse](Replace(A.Directory,'&','&'),'\') Order By Key_PS Desc) B 
) 
Select A.directoryId 
     ,ParentDirId =B.directoryId 
     ,A.Length 
     ,A.Directory 
    From cteBase A 
    Left Join cteBase B 
    on (B.Directory+'\'+Replace(A.Key_Value,'&','&') = Replace(A.Directory,'&','&')) 

返回

directoryId ParentDirId Length Directory 
7788  NULL  631  Y:\Foo 
3606  7788  70246 Y:\Foo\Bar 
3607  3606  70246 Y:\Foo\Bar\SomeDir & Date 

解析器UDF如果需要

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimeter varchar(10)) 
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',') 
--  Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ') 

Returns @ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max)) 
As 
Begin 
    Declare @XML xml;Set @XML = Cast('<x>' + Replace(@String,@Delimeter,'</x><x>')+'</x>' as XML) 
    Insert Into @ReturnTable Select ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM @XML.nodes('x') as T(String) 
    Return 
End 
+0

我創建了一個主源文件表與目錄ID已經存在得到這個返回: 消息9421,級別16,狀態1,行1個 XML分析:行1,字符96,非法命名字符 – VinnyGuitara

+0

我想這是因爲我在目錄名中含有一個符號,任何變通? – VinnyGuitara

+1

@VinnyGuitara有趣。剛剛用&創建了一個虛擬記錄並得到了相同的錯誤。給我一點時間 –