home

Check if file exists
Author Nigel Rivett

-- using the scripting object
declare	@Path varchar(128) ,
	@FileName varchar(128)
	select	@Path = 'C:\' ,
		@FileName = 'myfile.txt'

declare	@objFSys int
declare @i int
declare	@File varchar(1000)
	
	select @File = @Path + @FileName
	exec sp_OACreate 'Scripting.FileSystemObject', @objFSys out
	exec sp_OAMethod @objFSys, 'FileExists', @i out, @File
	if @i = 1
		print 'exists'
	else
		print 'not exists'
	exec sp_OADestroy @objFSys 
	
-- using xp_cmdshell
declare	@Path varchar(128) ,
	@FileName varchar(128)
	select	@Path = 'C:\' ,
		@FileName = 'myfile.txt'

declare @cmd varchar(1000)
	create table #a(s varchar(1000))
	
	select @cmd = 'dir /B ' + @Path + @FileName
	insert #a exec master..xp_cmdshell @cmd
	
	if exists (select * from #a where s = @FileName)
		print 'exists'
	else
		print 'not exists'
	drop table #a

-- using xp_fileexists
declare	@Path varchar(128) ,
	@FileName varchar(128)
	select	@Path = 'C:\' ,
		@FileName = 'myfile.txt'

declare @i int
declare	@File varchar(1000)
	
	select @File = @Path + @FileName
	exec master..xp_fileexist @File, @i out
	if @i = 1
		print 'exists'
	else
		print 'not exists'



home