Intercept the query that SqlCommand executes on the database
Is it somehow possible to intercept the query that a given SqlCommand is going to execute on the database?
I'd like to track for debugging purposes all queries tha开发者_高级运维t my Data class invokes, and can't find a clever way to do this.
I tried to use some weird "replace" of the sql command string, or appending the parameters with a funky
sb.AppendLine("@" + p.ParameterName + " = " + p.ToDebugString());
(with "ToDebugString()" being an extension method that does a "ToString()" with or without single quotes depending if it's a string or not)
But that seems kinda unprofessional, and it fails horribly when it encounters an
SqlDbType.Structured
parameter.
More or less, I'd like to intercept the DB call inside the application in the same way the SqlServer Profiler does inside the DB itself.
Thank you in advance.
BIG EDIT:
I know that given a simple query like this:
SELECT * FROM MyTable WHERE ID=@ID
Rather than running it like this:
SELECT * FROM MyTable WHERE ID=1234
The database actually runs the procedure like this:
DECLARE @ID int
SET @ID = 1234
SELECT * FROM MyTable WHERE ID=@ID
Can I intercept at application level this last block?
It sounds like you're wanting to see the parameters substituted directly in the query string "as it's done on the server". This is not possible, because the server never substitutes the parameters into the string. That's the beauty of parameterized queries: data is data, code is code, and never that twain shall meet.
Given a simple query like this:
SELECT * FROM MyTable WHERE ID=@ID
Rather than running it like this:
SELECT * FROM MyTable WHERE ID=1234
You can think of it as if the database actually runs a procedure like this:
DECLARE @ID int
SET @ID = 1234
SELECT * FROM MyTable WHERE ID=@ID
精彩评论