How to log multiple errors in TRY..CATCH? - sql-server

My application runs SQL scripts to load in data and when there's a problem with the file it's loading, it only logs the last error which doesn't contain the useful information about why the file won't load.
Example code:
BEGIN TRY
BULK INSERT MyTableName
FROM 'C:\MyFilename.txt'
WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR = '\n',
TABLOCK,
MAXERRORS=0,
ERRORFILE = 'C:\MyFilename_Errors.log'
)
;
END TRY
BEGIN CATCH
INSERT INTO MyErrorLog
SELECT ERROR_MESSAGE() as Issue
, ERROR_LINE() as IssueRowNum
;
END CATCH
This script will create an entry in [MyErrorLog] for the third error (see below). And the log file will tell me what line, but not what field:
Row 30539 File Offset 1910820 ErrorFile Offset 0 - HRESULT 0x80004005
Here's all 3 lines if I "THROW" the error inside the CATCH:
Msg 4864, Level 16, State 1, Line 3 Bulk load data conversion error
(type mismatch or invalid character for the specified codepage) for
row 1, column 5 (MyField).
Msg 7399, Level 16, State 1, Line 3 The OLE DB provider "BULK" for
linked server "(null)" reported an error. The provider did not give
any information about the error.
Msg 7330, Level 16, State 2, Line 3 Cannot fetch a row from OLE DB
provider "BULK" for linked server "(null)".
How do I capture that first (and second) error message?

You can only capture a single error in a T-SQL CATCH block. According to this connect item, the workaround is to use THROW (or not use TRY/CATCH) and capture the errors in client code.
Consequently, you'll need to invoke the script from a client application (including SQLCLR) so that you can capture and log all errors.

Related

Error in SQL Server updating Image datatype from a linked server

This is a table in a Microft Dynamics 2009 database. Our Test database is missing a bunch of Image data, so I would like to update the table in test with the data in production. I'm using this SQL for this update. When I execute this, I get this error:
Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 306, Level 16, State 2, Line 1
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
Query:
UPDATE INVENTTABLE
SET
Z_IMAGE = i2.Z_IMAGE,
Z_IMAGEMIMETYPE = i2.Z_IMAGEMIMETYPE
FROM INVENTTABLE i1
JOIN [PRODSQLSERVER].[DAX2009DB].[dbo].INVENTTABLE i2
ON i1.RECID = i2.RECID
WHERE i2.Z_IMAGE IS NOT NULL
I can't see a place where I'm attempting to compare or sort the Image data.
Try changing UPDATE INVENTTABLE to UPDATE i1.

Getting error when trying to use OPENQUERY Msg 7321, Level 16, State 2, Line 1

when i run this query
SELECT *
FROM OPENQUERY([XXX], 'SELECT * FROM Database.Table WHERE (MBCONO=650) AND MBCUNO LIKE a%' )
Get the Error :
OLE DB provider "DB2OLEDB" for linked server "XXX" returned message
"Token %ŸFOR SKIP WITH FETCH ORDER UNION EXCEPT OPTIMIZE SQLSTATE:
42601, SQLCODE: -104".
Msg 7321, Level 16, State 2, Line 1 An error
occurred while preparing the query "SELECT * FROM Database.Table WHERE
(MBCONO=650) AND MBCUNO LIKE a%'" for execution against OLE DB
provider "DB2OLEDB" for linked server "LAWSON".
But when I run the Same query Without AND MBCUNO LIKE a% Return Result !!
Any One Can Help Me About This Issue
Thanx
Have you tried putting escaped single quotes around the LIKE condition?
SELECT *
FROM OPENQUERY([XXX], 'SELECT * FROM Database.Table WHERE (MBCONO=650) AND MBCUNO LIKE ''a%''' )
If this doesn't work, try running the query directly against the target server.

sql azure beginner- getting error for an simple insert statement

I am trying to insert a row of data into a table in SQL Azure --
This is the insert statement--
INSERT INTO cloud_storage_credentials (cloud_provider,api_key, api_secret)
VALUES("Rackspace", "<random_value>", "<random_value>");
However I am getting the following error--
Msg 207, Level 16, State 1, Line 2
Invalid column name 'Rackspace'.
Msg 207, Level 16, State 1, Line 2
Invalid column name '<random_value>'.
Msg 207, Level 16, State 1, Line 2
Invalid column name '<random_value>'.
What am I doing wrong here? I followed an SQL Server tutorial to write the above query...
change the " (double quotes) to ' (tick/single quote)
INSERT INTO cloud_storage_credentials (cloud_provider,api_key, api_secret)
VALUES('Rackspace', '<random_value>', '<random_value>');
Change your "s with 's. As it is, it thinks that the values you are inserting are name of columns.

How to set SQLException Number

I'm having an issue on settin up SqlException.Number
On my Stored Proc i'm raising an error
--#number = 50001
RAISERROR(#number, 16, 1) -
I should expect that the Error_Number() should be #number but I always get 18054
Is there something wrong with my RAISERROR?
Check the sys.messages table for error code 74601. if this is a user defined error, it shouold be added in the table.
for any error that is greater than 50000 should give you this output if not found.
Msg 18054, Level 16, State 1, Line 1
Error XXXXX, severity 16, state 1 was raised, but no message with that error number was found in sys.messages. If error is larger than 50000, make sure the user-defined message is added using sp_addmessage.
There is one small caveat: You can't supply a message on your own in this case. But this can be circumvented by adding an additional %s in the sp_addmessage call or by changing all mapped messages to your own pattern and supplying the right parameters in the raiseerror call.
Check there for more information:
SQL Server: Rethrow exception with the original exception number
RAISERROR can either reference a user-defined message stored in the
sys.messages catalog view or build a message dynamically.
Check for your error message exists or not using this:
select * from sys.messages
If it does not exists then Use sp_addmessage to add user-defined error messages and sp_dropmessage to delete user-defined error messages.
for more information follow RaiseError documentation.

How to handle multiple errors

When I run something like
BACKUP LOG [somedb]
TO DISK = N'i:\log.bak';
It throws 2 errors messages:
Msg 3201, Level 16, State 1, Line 2
Cannot open backup device 'i:\log.bak'. Operating system error 3(The system cannot find the path specified.).
Msg 3013, Level 16, State 1, Line 2
BACKUP LOG is terminating abnormally.
When I try to handle the error with a TRY CATCH the error returned is always 3013. This is a problem for me because I want to know if the backup failed due to lack of space, or if the drive isn't present, etc.
Using ##ERROR returns the same error number.
Is there any way to handle multiple error messages like these?
You need to inspect the Errors collection inside the SqlException:
catch(SqlException sqlEx)
{
foreach(SqlError error in sqlEx.Errors)
{
int code = error.Number;
string msg = error.Message;
}
}
You should get all error with all relevant details in the SqlException.Errors

Resources