views:

510

answers:

2

I'm using Delphi 2007 with ADO to access a MS SQL 2008 database.

A stored procedure on the database prevalidates the input and if the validation fails it returns an error result set (containing custom error info). Uisng the SQL Server Management Studio, when I run the stored proc I get the custom error result set in one tab and the native error message in another.

Back in my Delphi app, when I open the stored proc, I can access the custom error result set. However, the "Errors" object on the ADO connection does not contain the native error.

How do I access the Errors collection object so I can provide more information about the cause of the error ?

Thanks

+1  A: 

Option 1) using the ADO Connection Errors collection.

try
....
....
....
 ADOQuery1.Open;//Execute your sql statement
except
  LastErrorIndex  :=ADOConnection1.Errors.Count-1;
  SourceError     :=ADOConnection1.Errors.Item[LastErrorIndex].Source;
  NumberError     :=ADOConnection1.Errors.Item[LastErrorIndex].Number;
  DescriptionError:=ADOConnection1.Errors.Item[LastErrorIndex].Description;
  SQLStateError   :=ADOConnection1.Errors.Item[LastErrorIndex].SQLState;
  NativeError     :=ADOConnection1.Errors.Item[LastErrorIndex].NativeError;
end;

Option 2) You can use the @@error variable to get the last error from sql server.

select @@error

When an error occurs in Sql Server, all you can get is the error number, using the @@ERROR global variable. There is no @@ERROR_MESSAGE global variable to get the error description. For a complete error message, you can query the master..sysmessages table using the error number:

SELECT Description FROM master..sysmessages  WHERE error= @@ERROR AND msglangid=1033

but most of these messages have place holders (like %s, %ld), you can also use this Stored Procedure.

you can read this article Error Handling in SQL Server – a Background for more information.

Bye.

RRUZ
Instead of `.sql.clear` and `.sql.add`, you could just say `.sql.text :=`
Mason Wheeler
Thanks RRUZ. I think the problem is that with ADO you can either retrieve a result set and/or and return value, OR an unhandled error occurs on the server which is returned as a native ADO error.I'll ask our dba to take another look and decide how we will return the error.
Good point Mason !
A: 

And here's a follow up question ....

The server is raising two errors (which I can see when running the code in SL Server Management Studio BUT the ADO errors collection only contains one error (the most recent one)

????

I found the answer to this one. Using the SQL Server native client provider (Provider=SQLNCLI10.1) in the connection string only returns one error in the collection. Using the vanilla OLEDB provider (Provider=SQLOLEDB.1) allows all errors to be read.