Thursday, January 25, 2018

sql server: FileTable and hierarchyid, insert folders and files into filetable by tsql

-- Filetablename: MyFile


--create testfolder
INSERT INTO MyFile (name, is_directory)   VALUES ('testFolder', 1)

--insert first file into testfolder:
DECLARE @ParentLocator as hierarchyid = (select path_locator from MyFile where parent_Path_locator is NULL and name like 'testfolder') --get parent
INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT 't2.txt', CONVERT(VARBINARY(MAX),'TestFileText'), @ParentLocator.GetDescendant(NULL,NULL) -- insert next child

DECLARE @ParentLocator as hierarchyid = (select path_locator from MyFile where parent_Path_locator is NULL and name like 'testfolder') --get parent

DECLARE @Child1Locator as hierarchyid = (select top 1 path_locator from MyFile where parent_Path_locator=@ParentLocator order by path_locator desc) -- get latest child

INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT 't2.txt', CONVERT(VARBINARY(MAX),'TestFileText'), @ParentLocator.GetDescendant(@Child1Locator,NULL) -- insert next child



No comments: