Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Script Library
 Function F_CHECK_IF_FILE_EXISTS

Author  Topic 

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-03-05 : 17:29:47
This function can be used to check if a file exists.

Works with SQL Server 2000, 2005, and 2008.

if object_id('dbo.F_CHECK_IF_FILE_EXISTS','FN') is not null
begin drop function dbo.F_CHECK_IF_FILE_EXISTS end
go
create function dbo.F_CHECK_IF_FILE_EXISTS
( @FILEPATH nvarchar(500) )
returns int
as
/*
Function F_CHECK_IF_FILE_EXISTS returns a 1
if the file passed in parameter @FILEPATH exists,
and returns a 0 if is does not exist.

It works with UNC names if the SQL Server
service account has access to the share.
*/

begin

declare @retcode int
declare @FILE_EXISTS int

exec @retcode = master.dbo.xp_fileexist
@FILEPATH,
@FILE_EXISTS output

return @FILE_EXISTS

end
go
print 'Check if file exists'

select [C:\autoexec.bat] = dbo.F_CHECK_IF_FILE_EXISTS('C:\autoexec.bat')

select [D:\autoexec.bat] = dbo.F_CHECK_IF_FILE_EXISTS('D:\autoexec.bat')

select [C:\autoexecx.bat] = dbo.F_CHECK_IF_FILE_EXISTS('C:\autoexecx.bat')


Results:
Check if file exists
C:\autoexec.bat
---------------
1

(1 row(s) affected)

D:\autoexec.bat
---------------
0

(1 row(s) affected)

C:\autoexecx.bat
----------------
0

(1 row(s) affected)






CODO ERGO SUM
   

- Advertisement -