title: Prevent sql injection in dynamic code
body: <p>I need to execute dynamic string with sql query from C# code and prevent sql injection.</p>
  
  <p>my code is like that:</p>
  
  <pre><code>internal static string Get_Running_Cars(string from, string to)
          {
              return string.Format(
                   " declare @from as datetime = '{0}'" +
                   " declare @to as datetime = '{1}'" +
                   " select  top 3 DATEDIFF(second,starttime,endtime) as sum,carname as name" +
                   " from cars" +
                   " where @from &lt; starttime and @to &gt; endtime ", from, to
                   );
          }
  </code></pre>
  
  <p>in that code I can insert malicious code into those string.</p>
  
  <p>how can I use it safely ?
  should I prevent those chars : <code>'</code>, <code>;</code>, <code>,</code> <code>-</code>?</p>