:xp_fileexists is a very useful undocumented stored procedure of SQL Server.
The usage of xp_fileexist is as follow
Exec xp_fileexist “E:\abc.txt”
The values returned are:
You can also use OUTPUT parameter to get the value of “File Exists” column as below:
Declare
@vFileExists
int
exec
master.dbo.xp_fileexist
'E:\abc.txt'
, @vFileExists
OUTPUT
Select
If you want to save all three returned values, then you will have to go through Temp Table approach:
Table
(FileExists
, FileDir
, ParentDirExists
)
insert
into
*
from
Sometimes xp_fileexist behaves abnormally. Your file is there and it does not check the file and returns 0 in FileExists column. This is an extended SP so its behavior may also change with different versions of SQL Server.
If you are facing the same problem, change you code with xp_cmdshell “dir” approach:
@vExistsPath nvarchar(100)
@files
([FileName] nvarchar(100))
Set
@vExistsPath =
''
'dir '
+ @vExistsPath +
' /b'
Insert
EXEC
xp_cmdshell @vExistsPath
if Exists(
1
where
[FileName] =
'abc.txt'
And
[FileName]
is
Not
Null
begin
end
else
0
The “/b” switch returns only filenames with extension as a result of “dir” command.