Wednesday 2 November 2016

Using Sql Profiler 2014 to debug SqlCommand in C#

I found the SqlCommand C# class is tricky to debug in Visual Studio if you are using SqlParameter and you want to see the exact statement being executed on the server.

First of all, run a test query on a table in the database, you will need to run your C# application to generate the query. This will create an entry in the process list for that database, which you can filter in Sql Profiler 2014.

select * from master..sysdatabases
select * from master.sysprocesses where dbid = 11

Look for the database id (dbid) of the database you ran the query on, and then find all processes running for that database. In my case, the dbid was 11 and I ran the query to get all processes for that database.

Scroll to the program_name and copy the value.
Note: Remove any extra spaces, as the Sql field in the result will be padded with spaces.

Getting program name.jpg



Open up the Profiler, create a new trace. In my case, I only want to see the final command being executed, so I ticked SQL:BatchCompleted only, and unticked all the other events.

Click 'Column Filters...', under 'ApplicationName' paste in the value you got from the process list (program_name).

Remember to remove any extra spaces, otherwise the Profiler will not be able to match it correctly, this is a common mistake!


New trace settings.jpg 


Run your trace and execute your Sql commands either from a test query or your C# application.

Trace completed2.jpg


You should notice that the commands are easily checked in Sql Profile 2014 now and you can test your C# application by matching its program_name from master..sysprocesses.

You can filter the events neatly to only show the application you are debugging by ticking SQL:BatchCompleted event and filtering by Column item ApplicationName.