Friday, February 24, 2012

Debugging SQL Server statements in code

How can I view the raw SQL code that ASP.NET sends to SQL Server when using parameters?
The code below doesn't display the actual SQL statement, but instead:System.Data.SqlClient.SqlCommand.

string SQL = "INSERT INTO [BLAH] VALUES (@.startDate)";
SqlConnection mySqlConn = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
SqlCommand mySqlCmd = new SqlCommand(SQL, mySqlConn);
mySqlCmd.Parameters.Add(new SqlParameter("@.startDate", SqlDbType.DateTime));
mySqlCmd.Parameters["@.startDate"].Value = Request.Form["start_date"];
lblSQLDebug.Text = mySqlCmd.ToString();
TIA.
Use SQL Profiler. It allows you to see all the SQL sent to the SQL Server. Very useful tool.|||Hi Douglas.
Following your suggestion, I setup the profiler. Unfortunately, itdoesn't receive my query before I receive the same ambigious error fromASP.NET.
Is it possible to gather the dynamic string assembled and sent to the database before it's actually executed?

|||If the query does not make it into SQL Profiler, then the problem is not a SQL Server problem. Whatexactlyis the error you are getting?|||

String was not recognized as a valid DateTime.

mySqlCmd.Parameters.Add(new SqlParameter("@.startDate", SqlDbType.DateTime));
mySqlCmd.Parameters["@.startDate"].Value = Request.Form["start_date"];
I'm using a third party component to generate the date via a pop-up calendar.
The line # of the error points here:
mySqlCmd.ExecuteNonQuery();
which seems to indicate that the SQL Query being sent to SQL Server isbad. I can't fix it until I know what the actual value of @.startDate isthat is being sent to the database server.
Thanks for helping me out.

|||This doesn't answer myquestion, but did help me debug. I enabled trace="true" and it allowedme to see how the control was submitting the values (different thanexpected).
I'm just surprised that ASP.NET doesn't have a method like RawQuerythat you could use to display the SQL before it's sent to the databaseprogramatically.
E.g., mySqlCmd.RawQuery.ToString();
I appreciate your support Douglas.
|||ASP.NET does not have such a facility. SQL Server does, but again, if the info does not get to SQL Server, of course it will not show up in the Profiler. You can, of course, debug the application and inspect values as they are added to the Parameters collection, or examine the entire Parameters collection in the debugger.

No comments:

Post a Comment