Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I was trying to write a SQL user defined function to check whether a file path passed to it exists or not.
SQL
CREATE FUNCTION [dbo].[IsExists](@FilePath nvarchar(MAX))
RETURNS int
AS
BEGIN
    DECLARE @File_Exists int;
    EXEC Master.dbo.xp_fileexist @FilePath, @File_Exists OUT;
    RETURN ISNULL(@File_Exists, 0);
END

This function is always returning Zero, regardless of whether the file exists or not. Could anyone help me to find where I went wrong! :(



Now, while checking this, I wrote the below given script (code snippet)
SQL
DECLARE @FilePath nvarchar(MAX);
SET @FilePath='C:\temp\ServiceLog.txt';

CREATE TABLE #FileExists (isExists int, isDirectory int, isParentDirExists int);

INSERT INTO #FileExists (isExists, isDirectory, isParentDirExists)
    EXEC Master.dbo.xp_fileexist @FilePath;

DROP TABLE #FileExists;

and it is throwing error!
Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
Any clue... :(

Regards
Sangeeth
Posted

1 solution

It works fine at my place

SQL
CREATE FUNCTION [dbo].[IsExists](@FilePath nvarchar(255))
RETURNS int
AS
BEGIN
    DECLARE @File_Exists INT;
    EXEC Master.dbo.xp_fileexist @FilePath, @File_Exists OUT;
    RETURN @File_Exists
END
GO

DECLARE @FilePath VARCHAR(255)= 'F:\data.txt'
SELECT [dbo].[IsExists] (@FilePath) AS FileExists
GO


FileExists
1

Running without using function

SQL
DECLARE @FilePath VARCHAR(255)= 'F:\data.txt'

CREATE TABLE #FileExists (isExists int, isDirectory int, isParentDirExists int);
INSERT INTO #FileExists (isExists, isDirectory, isParentDirExists)
EXEC Master.dbo.xp_fileexist @FilePath;

SELECT * FROM #FileExists

DROP TABLE #FileExists;


isExists	isDirectory	isParentDirExists
1	        0	        1


I Just have changed Nvarchar(Max) to Nvarchar(255)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900