1

I use the following code to check if one file exists in a folder and it works with returning 1.

Code A:

DECLARE @result INT
EXEC master.dbo.xp_fileexist 'C:\Users\folder\123.json', @result OUTPUT
SELECT @result

Now I want to a variable to represent the path and create the following code, but it does not work, returning error message saying

Msg 22027, Level 15, State 1, Line 2
Usage: EXECUTE xp_fileexist [, OUTPUT]

Code B:

DECLARE @rootfolder AS NVARCHAR(MAX),
        @file AS NVARCHAR(MAX)
declare @jsonfilename varchar(100)

set @rootfolder = 'C:\Users\folder\'
set @jsonfilename = '123.json'
set @file = concat(@rootfolder, @jsonfilename);

DECLARE @result INT
EXEC master.dbo.xp_fileexist @file, @result OUTPUT
select @result

If I print @file, it's exactly the same as what I want. Not sure what is the problem and how to fix it.

4

1 回答 1

1

Looks like xp_fileexist does not accept VARCHAR(MAX) or NVARCHAR(MAX) as input. I get the same error as you (SQL Server 2017 Ent.) but specifying the character length works:

DECLARE @rootfolder AS VARCHAR(max),
        @file AS NVARCHAR(255)
declare @jsonfilename varchar(100)

set @rootfolder = 'C:\Users\folder\'
set @jsonfilename = '123.json'
set @file = concat(@rootfolder, @jsonfilename);

DECLARE @result INT
EXEC master.dbo.xp_fileexist @file, @result OUTPUT
select @result

Starting in SQL Server 2017 there is also a new DMF sys.dm_os_file_exists() that does the same thing and does support MAX:

DECLARE @rootfolder AS VARCHAR(max),
        @file AS NVARCHAR(max)
declare @jsonfilename varchar(100)

set @rootfolder = 'C:\Users\folder\'
set @jsonfilename = '123.json'
set @file = concat(@rootfolder, @jsonfilename);

DECLARE @result INT
SELECT @result = file_exists FROM sys.dm_os_file_exists(@file)
于 2019-12-12T18:02:51.703 回答