Is there any way to intercept the SQL that's generated by SqlCommand?
I currently have a method that will execute a stored procedure:
public int ExecSP(string spName, params objec[] params)
{
using (SqlConnection con = new SqlConnection("AdventureWorks"))
using (SqlCommand cmd = new SqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
//..calls method to add params and values to cmd object
con.Open();
return cmd.ExecuteNonQuery();
}
}
When I use this to call the following:
ExecSP("HumanResources.uspUpdateEmployeePersonalInfo", 1, "295847284", new DateTime(1963, 3, 2), "S", "M");`
I get the following in SQLProfiler:
exec HumanResources.uspUpdateEmployeePersonalInfo @BusinessEntityID=1,@NationalIDNumber=N'295847284',@BirthDate='1963-03-02 00:00:00',@MaritalStatus=N'S',@Gender=N'M'
What I would like to do is intercept that SQL command so that I may add a comment to the end of it that will contain some pertinent information so that it looks like:
exec HumanResources.uspUpdateEmployeePersonalInfo @BusinessEntityID=1,@NationalIDNumber=N'295847284',@BirthDate='1963-03-02 00:00:00',@MaritalStatus=N'S',@Gender=N'M' -- IMPORTANT INFORMATION HERE
I can't change the CommandType to Text and I can't add an extra parameter to the stored procedure. I tried looking at these other questions but had no luck:
Can I override SqlCommand functions?
SqlCommand to T-SQL
In the case of CommandType = CommandType.StoredProcedure, this isn't possible.
Why? The SQL you see in SQL Profiler isn't generated by the client. :-/
When SqlCommand executes a CommandType.StoredProcedure command, it sends SQL Server an execute remote procedure call message with the name of the stored procedure and a data structure containing the parameters.
The TextData SQL Profiler displays for the RPC:Starting/RPC:Completed events is generated server-side. Since this text isn't generated client-side, it's not possible to modify it client-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With