How can I get the actual SQL that caused an SqlException in C#?

Zugwalt picture Zugwalt · Jan 28, 2011 · Viewed 10.7k times · Source

Possible Duplicate:
Obtain the Query/CommandText that caused a SQLException

I am working on some error handling code (using elmah) and the default setup only sends the error message. I would like to know the actual SQL that throws an error (i.e. "SELECT * FROM thisTableDoesNotExist")

This is what I have so far:

if (e.Error.Exception is SqlException)
{
    //if SQL exception try to give some extra information
    SqlException sqlEx = e.Error.Exception as SqlException;
    e.Mail.Body = e.Mail.Body + "<div>" +
                                "<h1>SQL EXCEPTION</h1>" +
                                "<b>Message</b>: " + sqlEx.Message +
                                "<br/><b>LineNumber:</b> " + sqlEx.LineNumber + 
                                "<br/><b>Source:</b> " + sqlEx.Source +
                                "<br/><b>Procedure:</b> " + sqlEx.Procedure +
                                "</div>";
}

And I would like to be able to also show the actual SQL. The database is SQL Server 2008 and SqlException is of type System.Data.SqlClient.SqlException.

Answer

Mike Atlas picture Mike Atlas · Jan 28, 2011

Not possible. You'll need to catch the exception where the SQL command was executed, and then include your command text in your own custom exception. See Obtain the Query/CommandText that caused a SQLException.