SqlCommand for T-SQL

Is there a way to convert a SqlCommand object into a real T-SQL command that is sent to SQL Server?

0
source share
2 answers

I don’t think that the parameters and query text are sent to SQL Server separately, and SQL Server communicates with them accordingly. You can get a request from SqlCommand.CommandText, and the parameters are stored in the SqlCommand.Parameters collection. You will need to do some string manipulation in order to turn them into a query, but even then you have something other than what is sent to SQL Server.

There is interesting information about this in this question: How does SqlCommand sanitize parameters?

0
source

- ( , ):

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();
}
0

Source: https://habr.com/ru/post/1769761/


All Articles