2012-07-31 47 views
34

Solución: http://www.tech-recipes.com/rx/30527/sql-server-how-to-check-if-a-file-exists-in-a-directory/¿Existe alguna verificación para el archivo en el servidor sql?

Hice una publicación sobre esta pregunta usando la pregunta de stackoverflow para ayudar a los demás.

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 

he tabla como ésta creada en mi servidor db, me he guardado rutas de archivos en ella FilePath columna, ahora tengo para comprobar el uso de SQL si existe el archivo en mi máquina, si es que existe I Necesito agregar una columna temporal en mi tabla que demuestre que sí existe y que no existe.

Escribí este código que funciona para 1 archivo pero no sé cómo usarlo para mi tabla.

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 

La salida final debe recibir este

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 
+0

Parece que usted está intentando utilizar un servidor SQL Server remoto para comprobar si existe un archivo en el equipo local. Es poco probable que el servidor tenga acceso al sistema de archivos en su máquina local (por una buena razón). – paul

Respuesta

71

crear una función de este modo:

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 

Edite su tabla y anuncio d una columna calculada (IsExists BIT). Establecer la expresión a:

dbo.fn_FileExists(filepath) 

A continuación, sólo seleccione:

SELECT * FROM dbo.MyTable where IsExists = 1 

actualización:

Para utilizar la función fuera una columna calculada:

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

Actualización:

Si la función devuelve 0 para un archivo conocido, es probable que haya un problema de permisos. Asegúrese de que la cuenta de SQL Server tenga suficientes permisos para acceder a la carpeta y los archivos. Solo lectura debería ser suficiente.

Y SÍ, de forma predeterminada, la cuenta 'SERVICIO DE RED' no tendrá suficiente en la mayoría de las carpetas. Haga clic derecho en la carpeta en cuestión y seleccione 'Propiedades', luego haga clic en la pestaña 'Seguridad'. Haga clic en 'Editar' y agregue 'Servicio de red'. Haga clic en 'Aplicar' y vuelva a probar.

+0

Intenté así 'SELECT * FROM fileinfo donde dbo.fn_FileExists (filepath) = 1;' filepath es mi columna pero devuelve vacío. –

+0

Necesita ser 'DECLARE @result INT' como declarar el parámetro de salida como' BIT' siempre devuelve 'NULL' para mí. –

+0

@ViswanathanIyer - no funcionará de esa manera, tiene que ponerlo en una columna calculada, o usarlo en la instrucción select –

2

no han sido evaluados pero se puede intentar algo como esto:

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 [email protected]) 
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 @[email protected]+1 
END 
0

Pruebe el siguiente código para verificar si el archivo existe. Puede crear una función de usuario y usarla en su procedimiento almacenado. modificarlo como sea necesario:

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 
0

se puede lograr esto mediante un cursor pero el rendimiento es mucho más lento que el bucle while .. Aquí está el código:

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 

o se puede poner en un TempTable si quieres integrarlo en tu interfaz ...

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 

luego llamarlo usando:

exec GetFileStatus 
+0

solo para agregar algunas cosas, si desea validar si el archivo existe en un servidor remoto, necesita compartir su carpeta (s) – devkiat

Cuestiones relacionadas