Problem with IF / BEGIN / ELSE I'm trying to run a select IF there's something inside a folder:
   INSERT INTO #tb (SubDirectory, Depth, [File])
   EXEC master..xp_dirtree 'C:\folder\', 10, 1

This will populate a table with the name of the file (if there's one inside the folder)
Then, if there's an Excel file there (or not) I will run this query:
IF (SELECT COUNT(1) FROM  #listavarejo) &gt; 0 
        SELECT *  FROM OPENROWSET('Microsoft.ACE.OLEDB.15.0','Excel.0;Database=C:\folder\excelfile.xlsx', [Planilha1$])
ELSE
        RAISERROR('NO FILES INSIDE FOLDER.',16,10);
    

The problem is, when I try to run this:
IF (SELECT COUNT(1) FROM  #listavarejo) &gt; 0 
        RAISERROR('there are file inside the folder.',16,10);
ELSE
        RAISERROR('theres no files inside the folder.',16,10);
    

It works perfectly. If there's a file inside the folder, the error &quot;there's is a file inside the folder&quot;, if there's no files, I can receive the error message after else.
But with the select * from openrowset, even with a file inside the folder or not, the query try to runs the select, and obviously I receive the error that the openrowset couldn't find the file.
Even using BEGIN/END I cant fix this.
I don't have an easy way to test this theory right now, but I'd bet that there are some validation checks of the OPENROWSET parameters going on when the batch compiles (the whole batch, regardless of IF / ELSE and whether or not those blocks eventually get executed).
Whenever I encounter this problem, using dynamic SQL is usually a solution.  Give that a shot:
IF (SELECT COUNT(1) FROM  #listavarejo) &gt; 0 
        EXEC sys.sp_executesql N'SELECT *  FROM OPENROWSET(''Microsoft.ACE.OLEDB.15.0'',''Excel.0;Database=C:\folder\excelfile.xlsx'', [Planilha1$])';
ELSE
        RAISERROR('NO FILES INSIDE FOLDER.',16,10);

This allows the code inside the dynamic SQL to be compiled only if it's executed.