3

Is it possible to see the sql statement after parameters have been replaced?

using(SqlCommand cmdInsert = new SqlCommand("INSERT INTO Table(Value_fkey) VALUES(@ValueKey)", Database.Connection))
{
    cmdInsert.Parameters.AddWithValue("@ValueKey", ValueKey);
    System.Convert.ToInt32(cmdInsert.ExecuteScalar());
}

I'd like it to log my sql statements, so rather not via SQL Server, but I don't mind whether it is before, or after calling the statement.

4
  • 1
    Parameters don't really get 'replaced', they just get used as parameters. You can loop through the existing parameters and see their values at any time. Commented Nov 4, 2012 at 13:19
  • possible duplicate stackoverflow.com/questions/2611446/… Commented Nov 4, 2012 at 13:19
  • 1
    Use the profiler to see what happens. You'll see one event prepare the statement, and another/others using that prepared statement, by ID. There is no substitution. Commented Nov 4, 2012 at 13:22
  • 1
    The sql you are looking for does not exist, will never exist. That is the whole point of using query parameters. Because this sql is never assembled, the chance of data in your query being mistakenly interpreted as code is zero. Commented Nov 5, 2012 at 0:03

1 Answer 1

2

This seems to be the simplest way to do it then:

public void OutputSQLToTextFile(SqlCommand sqlCommand)
{
        string query = sqlCommand.CommandText;
        foreach (SqlParameter p in sqlCommand.Parameters)
        {
            query = query.Replace(p.ParameterName, p.Value.ToString());
        }
        OutputToTextFile(query);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately this is wrong when using parameter with composed names such as @Par and @ParAdditional. In this case the Replace method will replace "@Par" and so we could have in the second parameter [valuie]Additional.
@peterboccia What if you were to sort the parameters from longest to shortest before replacing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.