Skip to main content

Update column with data from another table in SQL

 
At different point of time we come up with a situation 
where we need to update a column in a table from another
 table based on some condition.
 
So a Basic Syntax for update is:
UPDATE table
SET column1 = expression1,
    column2 = expression2,
    ...
[WHERE conditions];

For us to update based on another table we will be using the
same syntax for update  applying join with another table from
 where we need the data.


UPDATE t1
  SET t1.column_to_update= t2.column_from_update
  FROM Table1 t1
  INNER JOIN Table2 AS t2
  ON t1.common_column= t2.common_column
 

Comments

Popular posts from this blog

Using SqlDataAdapter to fill DataTable in c#

public DataTable List(string sql)         {             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);             SqlCommand cmd = new SqlCommand(sql, con);             DataTable dt = new DataTable();             SqlDataAdapter da = new SqlDataAdapter(cmd);             try             {                              con.Open();                 da.Fill(dt);             }             finally             {                 con.Close();          ...

Converting List to DataTable in C#

public static DataTable ConvertToDataTable<T>(IList<T> data)         {             PropertyDescriptorCollection properties =                TypeDescriptor.GetProperties(typeof(T));             DataTable table = new DataTable();             foreach (PropertyDescriptor prop in properties)                 table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);             foreach (T item in data)             {                 DataRow row = table.NewRow();                 foreach (PropertyDescriptor prop in properties)                     row[prop.Name]...