HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

Create Folder If Non Existent

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
folderexistentcreatenon

Problem

I need to check if a folder exists and if it does not create it. So if C:\CSV\red\ does not exist create, and so on. I use this DDL - how can I create folder if not there?

Create Table bonniebell
(
   name varchar(max)
)

Insert Into bonniebell values ('red'), ('blue'), ('green')

Declare @foldername varchar(max), @fulldirname varchar(max)

Declare folder cursor for

  Select name
  from bonniebell
  order by name asc

  Open folder

  fetch next from folder into @foldername

  while @@fetch_status = 0
  Begin

    Set @fulldirname = "C:\CSV\"

    Set @fulldirname = @fulldirname + @folder

  Fetch Next from folder into @foldername

  END

Close folder

Deallocate folder

Solution

You can use the extended stored proc "xp_dirtree". Store the results in a temp table and get the rowcount. Zero = not exists.

create table #Files(
subdirectory nvarchar(512),
depth int)

insert into #Files
exec xp_dirtree 'c:\windowsX'

select @@ROWCOUNT

drop table #Files

Code Snippets

create table #Files(
subdirectory nvarchar(512),
depth int)

insert into #Files
exec xp_dirtree 'c:\windowsX'

select @@ROWCOUNT

drop table #Files

Context

StackExchange Database Administrators Q#152013, answer score: 2

Revisions (0)

No revisions yet.