NEWS

[SQLSERVER] Sử dụng Store Procedure xp_dirtree để duyệt thư mục và tập tin trên hệ thống

[SQLSERVER] Sử dụng Store Procedure xp_dirtree để duyệt thư mục và tập tin trên hệ thống
Đăng bởi: Thảo Meo - Lượt xem: 5077 09:06:26, 17/10/2019C#   In bài viết

Xin chào các bạn bài viết hôm nay mình sẽ hướng dẫn các bạn sử dụng Store procedure Xp_dirtree trong sqlserver để liệt kê thư mục và tập tin trong hệ thống.

[SQLSERVER] Sử dụng Store Procedure xp_dirtree liệt kê thư mục và tập tin 

Cú pháp sử dụng xp_dirtree sql:

DECLARE @folderpath nvarchar(4000) = 'C:\Program Files\Microsoft SQL Server\'
EXEC master..xp_dirtree @folderpath
-- OR EXEC master..xp_dirtree 'C:\Program Files\Microsoft SQL Server\'

Kết quả khi thực hiện:

xp_dirtree_excute

Tiếp theo mình sẽ chia sẽ cho các bạn đoạn script sql, để khi truy vấn chúng ta sẽ biết được tập tin này thuộc thư mục nào.

Qua hai trường: IdparentID

DECLARE  @myPath VARCHAR(1000) = 'F:\xampp\htdocs\HOBWEB\IMG_loi_hangbosung'

DECLARE @DirectoryTree as TABLE (

	id int IDENTITY(1,1)

	,subdirectory nvarchar(512)

	,depth int

	,isfile bit

	, ParentDirectory int

	,flag tinyint default(0));

-- top level directory

INSERT  @DirectoryTree (subdirectory,depth,isfile)

VALUES (@myPath,0,0);

-- all the rest under top level

INSERT  INTO @DirectoryTree (subdirectory,depth,isfile)

EXEC master.sys.xp_dirtree @myPath,0,1 

UPDATE @DirectoryTree

	SET ParentDirectory = (

		SELECT MAX(id) FROM @DirectoryTree

		WHERE Depth = d.Depth - 1 AND Id < d.Id	)

FROM @DirectoryTree d;

-- SEE all with full paths

WITH dirs AS (

	 SELECT

		 Id,subdirectory,depth,isfile,ParentDirectory,flag

		 , CAST (null AS NVARCHAR(MAX)) AS container

		 , CAST([subdirectory] AS NVARCHAR(MAX)) AS dpath

		 FROM @DirectoryTree

		 WHERE ParentDirectory IS NULL

	 UNION ALL

	 SELECT

		 d.Id,d.subdirectory,d.depth,d.isfile,d.ParentDirectory,d.flag

		 , dpath as container

		 , dpath +'\'+d.[subdirectory]

	 FROM @DirectoryTree AS d

	 INNER JOIN dirs ON  d.ParentDirectory = dirs.id

)

SELECT * FROM dirs 

Các bạn, có thể truyền đường dẫn folder của các bạn muốn liệt kê qua tham số @myPath.

Kết quả khi chúng ta chạy câu lệnh trên:

xp_dirtree_sql

Thank for watching!

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[SQLSERVER] Sử dụng Store Procedure xp_dirtree để duyệt thư mục và tập tin trên hệ thống
Đăng bởi: Thảo Meo - Lượt xem: 5077 09:06:26, 17/10/2019C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.