之前,I requested how to create a directory within a FileTable
without using File I/O APIs 。我现在想为刚刚创建的父目录创建一个子目录。在插入期间如何分配我的 parent ?看来 parent_path_locator
是一个计算列。
这创造了我的 parent ......
INSERT INTO FileTable0 (name,is_directory,is_archive) VALUES ('Directory', 1, 0);
如何在我的 FileTable 中创建此父目录的子目录?
最佳答案
这就是我最终用来创建子目录的方法,因为 GetPathLocator()
不会为我生成新的 path_locator
值 - 它只会解释现有的 hierarchyids
.
DECLARE @parentdir table(path hierarchyid not null);
DECLARE @subdir_locator hierarchyid
-- Create Parent Directory, OUTPUT inserted parent path
INSERT INTO FileTable0 (name,is_directory,is_archive)
OUTPUT INSERTED.path_locator into @parentdir
SELECT 'Directory', 1, 0
-- Create new path_locator based upon parent
SELECT @subdir_locator = dbo.GetNewPathLocator(path) from @parentdir
-- Create Subdirectory
INSERT INTO FileTable0 (name,path_locator,is_directory,is_archive)
VALUES ('subdirectory', @subdir_locator, 1, 0);
上面的代码块使用default path_locator value discovered here从 GUID 构建新的 hierarchyid
表示(利用 newid()
方法和简单的解析)。我在 SQL Server 中找不到函数 GetNewPathLocator()
( hierarchyid.GetDescendant()
是我能找到的最接近的函数,但它没有使用 FileTable 所依赖的 native 结构)。也许在 SQL.NEXT 中...
CREATE FUNCTION dbo.GetNewPathLocator (@parent hierarchyid = null) RETURNS varchar(max) AS
BEGIN
DECLARE @result varchar(max), @newid uniqueidentifier -- declare new path locator, newid placeholder
SELECT @newid = new_id FROM dbo.getNewID; -- retrieve new GUID
SELECT @result = ISNULL(@parent.ToString(), '/') + -- append parent if present, otherwise assume root
convert(varchar(20), convert(bigint, substring(convert(binary(16), @newid), 1, 6))) + '.' +
convert(varchar(20), convert(bigint, substring(convert(binary(16), @newid), 7, 6))) + '.' +
convert(varchar(20), convert(bigint, substring(convert(binary(16), @newid), 13, 4))) + '/'
RETURN @result -- return new path locator
END
GO
函数 GetNewPathLocator()
还需要一个 SQL View getNewID
,以便使用 trick from this SO post 请求 newid()
.
create view dbo.getNewID as select newid() as new_id
要调用 GetNewPathLocator()
,您可以使用默认参数来生成新的 hierarchyid
或传入现有的 hierarchyid
字符串表示形式(.ToString()
) 创建子 hierarchyid
如下所示...
SELECT dbo.GetNewPathLocator(DEFAULT); -- returns /260114589149012.132219338860058.565765146/
SELECT dbo.GetNewPathLocator('/260114589149012.132219338860058.565765146/'); -- returns /260114589149012.132219338860058.565765146/141008901849245.92649220230059.752793580/
关于sql - 使用 FileTable 通过 SQL INSERT 创建子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485978/