60

Solution : http://www.tech-recipes.com/rx/30527/sql-server-how-to-check-if-a-file-exists-in-a-directory/

Made a post about this question using stackoverflow question to help others.

id  filepath

1   C:\vishwanath\21776656.docx
2   C:\vishwanath\vish\s_srv_req_2009.txt
3   C:\Users\dalvi\DW\DW20SharedAmd64.exe
4   C:\Users\dalvi\1.txt

I've table like this created in my db server, I've stored file paths in it filepath column, now I've to check using sql whether the file exists in my machine, if it exists I need to add temporary column in my table showing yes if exists and no it doesn't exists.

I wrote this code which works for 1 file But I don't know how to use it for my table.

DECLARE @isExists INT
exec master.dbo.xp_fileexist 'C:\vishwanath\21776656.docx', 
@isExists OUTPUT
SELECT case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists

The Final output should like this

id  filepath                                 Isexists

1   C:\vishwanath\21776656.docx               Yes
2   C:\vishwanath\vish\s_srv_req_2009.txt     Yes
3   C:\Users\dalvi\DW\DW20SharedAmd64.exe     Yes
4   C:\Users\dalvi\1.txt                      No
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
  • It sounds like you are trying to use a remote SQL Server to check whether a file exists on your local machine. It is unlikely that the server has any access to the filesystem on your local machine (for good reason). – paul Jul 31 '12 at 13:03

4 Answers4

123

Create a function like so:

CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
     DECLARE @result INT
     EXEC master.dbo.xp_fileexist @path, @result OUTPUT
     RETURN cast(@result as bit)
END;
GO

Edit your table and add a computed column (IsExists BIT). Set the expression to:

dbo.fn_FileExists(filepath)

Then just select:

SELECT * FROM dbo.MyTable where IsExists = 1

Update:

To use the function outside a computed column:

select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable

Update:

If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.

And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.

Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
  • I tried like this `SELECT * FROM fileinfo where dbo.fn_FileExists(filepath)=1;` filepath is my column but it returns empty. – Vishwanath Dalvi Jul 31 '12 at 12:50
  • Needs to be `DECLARE @result INT` as declaring the output param as `BIT` it always returns `NULL` for me. – Martin Smith Jul 31 '12 at 12:51
  • @ViswanathanIyer - won't work that way, you have to put it in a computed column, or use it the select statement – Chris Gessler Jul 31 '12 at 12:51
  • @MartinSmith - I updated my answer, and will test it shortly. – Chris Gessler Jul 31 '12 at 12:53
  • @ChrisGessler Still I'm getting `NULL` in all rows. – Vishwanath Dalvi Jul 31 '12 at 13:02
  • @ViswanathanIyer - the function should never return null, only 1 or 0. Test your function outside the computed column to see what it returns. If you still get null, I'd say you have a file permissions issue. – Chris Gessler Jul 31 '12 at 13:06
  • @ChrisGessler yeah I tried `select dbo.fn_FileExists(filepath) from fileinfo ` Still returns NULL. – Vishwanath Dalvi Jul 31 '12 at 13:07
  • @ViswanathanIyer - then you probably have a file permissions issue. Set access on the folder (and all content) to allow your SQL user to have read permissions. – Chris Gessler Jul 31 '12 at 13:09
  • it there any method to check file exit on url – Trikaldarshiii Jun 23 '13 at 08:58
  • I've this function working well but when I change the SQL user it returns allways 0 for all the records. Like you said, it's probably a permission issue - the windows user have access to the folders and files (added permissions to Network Services) but I don't know how can I change permissions in the SQL user. Any help? – PJLG Sep 12 '18 at 20:43
  • @PJLG - I'm not entirely certain how to manage those permissions or how to determine if the "Network Service" user can execute that function. Sounds like a good question to ask on stackoverflow. – Chris Gessler Sep 13 '18 at 00:14
  • Thanks @Chris. I think I've found the solution - at least it solved, although I did not realize all the implications. I had to activate the Server Role "Sysadmin" on the user in question (in Security outside DB). – PJLG Sep 13 '18 at 10:35
  • Thanks,But can u provide us t-sql function to check if directory is exists? – Zeinab Nov 07 '18 at 16:48
  • 1
    @Zeinab - check this link https://stackoverflow.com/questions/13765911/how-do-i-check-if-a-directory-exists-using-sql-server – Chris Gessler Nov 07 '18 at 20:03
2

Not tested but you can try something like this :

Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))

while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile , 
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists
set @count=@count+1
END
praveen
  • 12,083
  • 1
  • 41
  • 49
1

You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:

set nocount on
declare cur cursor local fast_forward for
    (select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;

fetch from cur into @fullpath
while @@FETCH_STATUS = 0
    begin
        exec xp_fileexist @fullpath, @isExists out
        if @isExists = 1            
            print @fullpath + char(9) + char(9) + 'file exists'
        else            
            print @fullpath + char(9) + char(9) + 'file does not exists'
        fetch from cur into @fullpath
    end
close cur
deallocate cur

or you can put it in a tempTable if you want to integrate it in your frontend..

create proc GetFileStatus as
begin
    set nocount on
    create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
    declare cur cursor local fast_forward for
        (select filepath from Directory)
    open cur;
    declare @fullpath varchar(250);
    declare @isExists int;

    fetch from cur into @fullpath
    while @@FETCH_STATUS = 0
        begin
            exec xp_fileexist @fullpath, @isExists out
            if @isExists = 1                
                insert into #tempFileStatus values(@fullpath,'File exist')
            else
                insert into #tempFileStatus values(@fullpath,'File does not exists')
            fetch from cur into @fullpath
        end
    close cur
    deallocate cur
    select * from #tempFileStatus
    drop table #tempFileStatus
end

then call it using:

exec GetFileStatus
devkiat
  • 139
  • 2
  • 6
  • 16
  • 1
    just to add few things, if you want to validate if file exist in a remote server, you need to share your folder(s) – devkiat Apr 25 '13 at 03:14
0

Try the following code to verify whether the file exist. You can create a user function and use it in your stored procedure. modify it as you need:

Set NOCOUNT ON

 DECLARE @Filename NVARCHAR(50)
 DECLARE @fileFullPath NVARCHAR(100)

 SELECT @Filename = N'LogiSetup.log'
 SELECT @fileFullPath = N'C:\LogiSetup.log'

create table #dir

(output varchar(2000))

 DECLARE @cmd NVARCHAR(100)
SELECT @cmd = 'dir ' + @fileFullPath     

insert into #dir    

exec master.dbo.xp_cmdshell @cmd

--Select * from #dir

-- This is risky, as the fle path itself might contain the filename
if exists (Select * from #dir where output like '%'+ @Filename +'%')

       begin    
              Print 'File found'    
              --Add code you want to run if file exists    
       end    
else    
       begin    
              Print 'No File Found'    
              --Add code you want to run if file does not exists    
       end

drop table #dir
Community
  • 1
  • 1
Shivkant
  • 4,509
  • 1
  • 19
  • 16