SqlCommand to T-SQL

前端 未结 2 1831
既然无缘
既然无缘 2021-01-26 17:41

Is there any way how to convert SqlCommand object to actual T-SQL command, which is sent to the SQL Server?

相关标签:
2条回答
  • 2021-01-26 18:03

    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();
    }
    
    0 讨论(0)
  • 2021-01-26 18:04

    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?

    0 讨论(0)
提交回复
热议问题