A way to see query after parameters are applied?

If you want to see the query with parameters applied:

string tmp = command.CommandText.ToString();
foreach (SqlParameter p in cmd.Parameters) {
    tmp = tmp.Replace('@' + p.ParameterName.ToString(),"'" + p.Value.ToString() + "'");
}

tmp will then hold the query with the parameters applied. Each parameter will be surrounded by single quotes.

Of course, it is NOT safe to execute. I use it for debugging purposes.


There's no guarantee that there is such a thing as "the query with the parameters applied". I would hope that a driver would simply send down the command as SQL and the parameters in an appropriate form to represent each value. Why go to the bother of escaping values etc, only for the query processor to unescape them and parse them at the other side? It's more efficient and less risky to just pass the data in a binary format of some description.

You should regard it as some code (the SQL) which uses some data (the parameters) and keep the two concepts very separate in your mind. If you need to log what's going on, I would log it as the parameterized SQL and the parameter values separately.