title: How to fix Inline C# query that is prone to SQL injection
body: <p>Following is my query that I wrote in order to get a simple max value for a given where clause. </p>
  
  <p>The only problem is it has to go through a veracode scan which determines if the query is prone to any SQL injection. </p>
  
  <p>This is my query </p>
  
  <pre><code>string strconnectionString = @Data Source = xxx\server; Initial Catalog =DBname;
  </code></pre>
  
  <p>These are user inputs I am just hardcoding for now </p>
  
  <pre><code>private DateTime? GetFirmsLastDate()
  {
      // My user inputs hardcoded for now 
      string tableName = "abc";
      string columnName = "CalculationTable";
      string filterColumn = "CalcValue";
      string firmName = "Bank1";
  
      using(SqlConnection connection = new SqlConnection(strconnectionString)
      {
          using(Sqlcommand cmd = new SqlCommand())
          {
              cmd.Connection = connection;
              cmd.CommandType = System.Data.CommandType.Text;
  
              cmd.CommandText = String.Format(@"Select MAX(K.{3}) FROM {1} K WHERE K.{2} ={0}" ,
                                               Sanitizer.GetSafeHtmlFragment(firmName), 
                                               Sanitizer.GetSafeHtmlFragment(tableName),
                                               Sanitizer.GetSafeHtmlFragment(filterColumn),
                                               Sanitizer.GetSafeHtmlFragment(column)
  
              connection.Open();
              object dateVal = cmd.ExecuteScalar();
  
              return (dataVal != DBNull.Value) : DateTime.Parse(dateVal.ToString()) : null;
          }
      }
  }
  </code></pre>
  
  <p>Why I had to use the inline query is <code>TableName</code>. It  is a textbox where the user can enter the table name. I cannot specify the <code>tableName</code> as a parameter for that purpose i have to prepare my statement when passing a <code>SqlCommand</code>. </p>
  
  <p>Thank you for your time.</p>