简体   繁体   中英

SQL Server ADO.Net retrieve error information from sql script

I am working on a project where we have to query an old SQL Server 2000 database (PeopleSoft, if you must know). The query returns a resultset. If we were on a newer database, I would use stored procedures and error handling (eg @ErrNo, @ErrMsg, Try/Catch) to get what I want.

However, we are on SQL Server 2000 and we are NOT allowed to use stored procedures, so we are left with only using dynamic SQL queries and scripts. We are currently using ADO.Net (eg DbCommand and Execute methods on it) to get our resultset.

What I'd like to do is put more error handling / validation in our sql scripts and return messages to our .Net code. (eg input value not valid, row not found, etc.)

Does anyone know how to do this under these contraints? If there are no easy ways to do this, can you recommend some alternatives? eg

  1. ask the DBA to create a specialized message / logging table for us and in our scripts, write to that table and in our code, read that table

  2. break up our code / scripts into multiple steps and call it from our .Net code (would we then have to use transactions?)

  3. etc. etc.? Really banging my head here...

Thanks everyone.

Stored procedures have little to do with what (I feel) you trying to achieve. Even if you have Error handling in stored procedure, you still going to send invalid data to get error handled. Seems, what you need is better "before DB call" validation.

What you can do to improve your situation is to utilize Ado.net to great extent. Specifically - use DataTables . You can load schema and it will create your DataTable in shape of your Sql Table. Check the properties of the DataTable Column object http://msdn.microsoft.com/en-us/library/system.data.datacolumn_properties%28v=vs.90%29.aspx

If you try to insert invalid data into this table first, it will error out and you will be able to create specific error handling.

Also, you can (and should) replace dynamic sql with parametrized query. This is recommended way and will improve performance.

Instead of :

"select * from customer where id = " + custId.ToString()

You should do:

"select * from customer where id = @1"

Then, when you create your command object, you will add a parameter. This is good for Sql Server performance.

While for you, DataTable will be line of defense against sending erroneous code to server.

Another way is writing entirely your own data validation logic based on INFORMATION_SCHEMA .

Another way is to have really strict data input validation.

Normally, systems have both, input validation and data layer validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM