I still think that the CLR procedure might be the best choice. So, I accept this answer. Nevertheless, either I am not so bright, or it is very difficult to implement. Our SQL Server service runs under a local account because, according to Mircosoft, this is the only way to get an iSeries server running a 64-bit instance of SQL Server 2005. When we change the SQL Server service to start with a domain account, the xp_fileexist command works great for files located on the network.
I created this CLR stored procedure and built it with the permission level set to External, and signed it:
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Security.Principal; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void FileExists(SqlString fileName, out SqlInt32 returnValue) { WindowsImpersonationContext originalContext = null; try { WindowsIdentity callerIdentity = SqlContext.WindowsIdentity; originalContext = callerIdentity.Impersonate(); if (System.IO.File.Exists(Convert.ToString(fileName))) { returnValue = 1; } else { returnValue = 0; } } catch (Exception) { returnValue = -1; } finally { if (originalContext != null) { originalContext.Undo(); } } } }
Then I ran the following TSQL commands:
USE master GO CREATE ASYMMETRIC KEY FileUtilitiesKey FROM EXECUTABLE FILE = 'J:\FileUtilities.dll' CREATE LOGIN CLRLogin FROM ASYMMETRIC KEY FileUtilitiesKey GRANT EXTERNAL ACCESS ASSEMBLY TO CLRLogin ALTER DATABASE database SET TRUSTWORTHY ON;
Then I deployed the CLR-stored copy to my target database from Visual Studio and used this TSQL to execute from SSMS registered with Windows Authentication:
DECLARE @i INT --EXEC FileExists '\\\\server\\share\\folder\\file.dat', @i OUT EXEC FileExists 'j:\\file.dat', @i OUT SELECT @i
Whether I tried a local file or a network file, I always get 0. I can try again later, but now I will try to go a different path. If someone has some light to shed, that would be very appreciated.
source share