C# .NET - Dynamic query in sql using c# - Asked By pravin on 05-Dec-12 03:52 AM

I wanna learn about dynamically building query fro sql using c#.Any one guide me...
Hemanth Kumar replied to pravin on 05-Dec-12 04:51 AM
Hi Pravin ,

You can generate the SQL Query dynamically
private string GetSql( IList<int> machineIds )
{
  var sql = new StringBuilder( "SELECT FileID FROM Files Where MachineID In(" );
  for( var i = 0; i < machineIds.Count; i++ )
  {
    if ( i > 0 )
      sql.Append(", ")
    sql.Append("@MachineId{0}", i);
  }
 
  sql.Append(" ) ");
 
  //additional parameters to query
  sql.AppendLine(" And Col1 = @Col1" );
  sql.AppendLine(" And Col2 = @Col2 ");
  ...
 
  return sql.ToString();
}