Question

I create a table in my stored procedure, export its content using BCP and then drop this table. BCP command looks like:

SET @sqlop = 'BCP "SELECT blah FROM MYTABLE" queryout "' + @txt4print* 
             + '" -b 50000 -c -t"," -S"server" -U"uname" -P"pswd"'
exec master..xp_cmdshell @sqlop       --, NO_OUTPUT

Typically, if there is an error in the store procedure, it is printed as a Message in SQL Server. However, the output from BCP is not printed as a message. So I'm not able to capture the error instance in MATLAB. Is there a way to catch the string error as shown below? Can this output be returned as a Message from SQL Server? enter image description here

I'm not an advanced SQL programmer. Thanks!

Was it helpful?

Solution

Well you have output here so you should be able to capture that output and then manually force an error from it.

DECLARE @Output TABLE (OutputMessage NVARCHAR(4000));

SET @sqlop = 'BCP "SELECT blah FROM MYTABLE" queryout "' + @txt4print* 
             + '" -b 50000 -c -t"," -S"server" -U"uname" -P"pswd"'

INSERT INTO @Output
exec master..xp_cmdshell @sqlop       --, NO_OUTPUT

DELETE FROM @Output WHERE OutputMessage IS NULL

DECLARE @Statement NVARCHAR(MAX)

WHILE (SELECT COUNT(*) FROM @Output) > 0
BEGIN
    SELECT TOP 1 @Statement = OutputMessage FROM @Output
    IF @Statement LIKE '%Error%'
    BEGIN
      SET @Statement = 'Unexpected error in procedure: ' + @Statement
      RAISERROR(@Statement, 16, 1)
    END
END

Alternatively if you just want a message and not an error, you should be able to use PRINT for similar effect.

http://technet.microsoft.com/en-us/library/ms176047.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top