The question is a bit vague with regards to how BCP is being executed, outside of it being done within a Stored Procedure. But since that is all we really know at the moment, I will assume that you are calling BCP.EXE
from xp_cmdshell
.
If you want to simply capture actual errors being thrown by BCP
, then that is very easy to do since the ERRORLEVEL
value is returned as an INT
from the xp_cmdshell
stored procedure:
DECLARE @ErrorLevel INT;
EXEC @ErrorLevel = xp_cmdshell
N'BCP "SELECT * FROM sys.objects where 1= " queryout C:\temp\BCPtest.txt -T -w ';
SELECT @ErrorLevel;
Returns:
1
If, however, you want to treat queries that complete successfully yet return 0 rows as an "error" condition, then that can also be done, it just requires a little more effort:
DECLARE @ErrorLevel INT;
EXEC @ErrorLevel = xp_cmdshell
N'BCP "SELECT * FROM sys.objects where 1= 0 " queryout C:\temp\BCPtest.txt -T -w && (FORFILES /P C:\TEMP\ /M BCPtest.txt /C "CMD /C IF @fsize LSS 3 DEL C:\TEMP\BCPtest.txt" & IF NOT EXIST C:\temp\BCPtest.txt EXIT -3)';
SELECT @ErrorLevel;
Returns:
-3
Please note that the long command-line needs to be either kept as a single line, or placed into a .CMD
script so that it works properly.
The additional logic, in a more readable format, is:
&& (
FORFILES /P C:\TEMP\
/M BCPtest.txt
/C "CMD /C IF @fsize LSS 3 DEL C:\TEMP\BCPtest.txt"
& IF NOT EXIST C:\temp\BCPtest.txt EXIT -3
)
Explanation: