Home > DTS > DTS SQL Statement / Stored procedure / Function to check for existence of file.

DTS SQL Statement / Stored procedure / Function to check for existence of file.

October 30th, 2006 Leave a comment Go to comments
CREATE FUNCTION [dbo].[fn_FileExists] (@FileName nvarchar(255))
RETURNS bit AS
BEGIN
	DECLARE @FS int
	DECLARE @FileID int
	DECLARE @OLEResult int
	declare @Exists bit

	EXECUTE @OLEResult = sp_OACreate 'Scripting.FileSystemObject', @FS OUT
	IF @OLEResult <> 0
	BEGIN
		RETURN 0
	END

	EXECUTE @OLEResult = sp_OAMethod @FS, 'FileExists', @Exists OUT, @FileName

	IF @OLEResult <> 0
	BEGIN
		return 0
	END
	EXECUTE @OLEResult = sp_OADestroy @FS

	return @Exists
END

Important things to remember.

  1. Existence of the file will be checked on the server in which it is created. If you are running this stored procedure on remote machine, it will check for file on remote machine and not on local machine.
  2. To call a function, you should write
    if dbo.fn_FileExists ('Filename.txt') = 1
    	print 'exist'

    Here “dbo.” must be appended to call the function, otherwise it will give error.

Categories: DTS Tags:
  1. June 21st, 2007 at 02:44 | #1

    Thanks for your share. This is i’m looking for.PS:i have another question?what is the system on blog.vishalon.net ?

  2. steve
    September 15th, 2009 at 03:33 | #2

    /*
    to avoid error:
    SQL Server blocked access to procedure ‘sys.sp_OACreate’ of component ‘Ole Automation Procedures’
    */
    – run this:
    sp_configure ‘show advanced options’, 1;
    GO
    RECONFIGURE;
    GO

    sp_configure ‘Ole Automation Procedures’, 1;
    GO
    RECONFIGURE;
    GO

  3. james
    January 13th, 2012 at 09:36 | #3

    Hello, Will it be possible to perfprm DTS by using T-sql statement?
    Regards

  1. No trackbacks yet.