Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create string using array,
Ex: update table set name=@name,address=@addr,age=@age etc.
I want to create this command using array because every time the update command is different for different tables. So i want to write command only one time.

Please any one help me in this regard.

Thanks in Advance
Posted
Updated 16-May-11 19:36pm
v2

1 solution

use Dictionary for this put column name as key and the corresponding value-
void Runcommand(string tableName,Dictionary<string,object>updatevalues, string wherecaluse)
{
  SqlCommand cmd=new SqlCommand(conn);
  cmd.CommandText="update "+tableName +" Set ";
  bool isAdded=false;
  foreach(string key in updatevalues.keys)
  {
    if(isAdded)
    {
      cmd.CommandText+=", ";
    }
    isAdded=true;
    cmd.CommandText+=string.Format("{0}=@{0}",
    cmd.Parameters.Add(new SqlParameter(key,updatevalues[key]);
  }
  cmd.CommandText+=" where "+whereclause;
  cmd.ExcuteNonQuery();
  
}


hope this will work for you.
 
Share this answer
 
v3
Comments
Robert Rohde 17-May-11 1:45am    
You forgot to set isAdded to true.
pankajupadhyay29 17-May-11 4:41am    
oh yes thanks.
rahul dev123 17-May-11 1:55am    
Thanks for your help but its not clear for me. If you don't mind please help me to sending the details code
pankajupadhyay29 17-May-11 4:43am    
this is all you need to create the command dynamically, which part is not clear to you??
parmar_punit 17-May-11 5:13am    
Where you add the SET and WHERE clauses in the CommandText??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900