Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Statement after adding parameters

Tags:

c#

sql

parameters

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.

like image 671
Richard Whitehouse Avatar asked Feb 20 '26 14:02

Richard Whitehouse


1 Answers

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);
    }
like image 195
Richard Whitehouse Avatar answered Feb 22 '26 04:02

Richard Whitehouse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!