Query The Folder System With xp_dirtree

Here’s a short piece of SQL Logic that will give you a list of folders, or files from any directory. All you need is access rights to those folders either from the SQL Service account or your regular use account MyDomain\MyUserName.

use master;
set nocount on

if object_id('tempdb..#folderandfileinfo') is not null
drop table #folderandfileinfo

create table #folderandfileinfo
cid int identity(1,1) primary key clustered
,	subdirectory	varchar(255)
,	depth int
,	isfile int

declare @path	varchar(255)
set @path	= '\\MyBackupShare\MyFolderName' -- insert your path here.

insert into #folderandfileinfo
,	[depth]
,	[isfile]
exec master..xp_dirtree
,	1
,	1

,	depth
,	'object' = case isFile when '1' then 'File' when '0' then 'Folder' end from
subdirectory like '%.bak'

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s