SqlCommand to T-SQL
Is there any way how to convert SqlComman开发者_如何学Pythond object to actual T-SQL command, which is sent to the SQL Server?
I don't think so, the params and query text are sent to SQL Server separately, and SQL Server deals with them accordingly. You can get the query from SqlCommand.CommandText, and the params are stored in the SqlCommand.Parameters collection. You'd have to do some string manipulation to turn it into a query, but even then you have something different than what's sent to SQL Server.
This question has some interesting information about this, too: How does SqlCommand sanitize parameters?
I was actually thinking about something like this extension (not working well, just idea):
public static string ToQuery(this SqlCommand command)
{
StringBuilder sb = new StringBuilder();
sb.Append("exec ");
sb.Append(command.CommandText);
List<string> parameters = new List<string>();
for (int i=0; i<command.Parameters.Count;i++)
{
if (command.Parameters[i].Direction != ParameterDirection.ReturnValue)
{
parameters.Add(string.Format(" {0}={1}", command.Parameters[i].ParameterName, command.Parameters[i].Value));
}
}
if (parameters.Count > 0) sb.Append(string.Join(",", parameters.ToArray()));
return sb.ToString();
}
精彩评论