Wednesday, August 22, 2007

Check if file exists using sql



-- 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'

1 comment:

Unknown said...

Hi. I am trying to get the [xp_fileexist] to work for a SQL account. When I run the following command as me with dbo rights...

exec master.dbo.[xp_fileexist] '\\remoteserver\sharedfiles\mypicture.jpg'

It return correctly one row with this values: 1 0 1

But, when I run it as the SQL user 'Sales', I get...
0 0 0.

What gives?