Search code examples
c#dataadapter

C#- Updating just updated column(s)


I have a web form. There are 20 fields that correspond to the columns in a database table. Let's say there's one record that has a BIRTHDATE column and I change its value from 13-July-2000 to 12-FEB-1985. But I don't touch the rest of the columns. Is there a way in C# to run an update statement like this:

UPDATE TABLE1 SET BIRHDATE=NEWVALUE WHERE ID=1111

instead of updating all the columns of the row like this:

UPDATE TABLE1 SET COLUMN1=NEWVALUE1, COLUMN2=NEWVALUE2,......,BIRTHDATE=NEWVALU

I think it would be a waste of resource. Am I wrong? I think DataAdapters are for this purpose but I'm not sure.


Solution

  • You can send a direct update statement to the Oracle Engine in this way.

    using (OracleConnection cnn = new OracleConnection(connString)) 
    using (OracleCommand cmd = new OracleCommand("UPDATE TABLE1 SET BIRHDATE=:NewDate WHERE ID=:ID", cnn)) 
    { 
            cmd.Parameters.AddWithValue(":NewDate", YourDateTimeValue);
            cmd.Parameters.AddWithValue(":ID", 111);
            cnn.Open(); 
            cmd.ExecuteNonQuery(); 
    }
    

    EDIT:

    If you don't know which fields are changed (and don't want to use a ORM Tool) then you need to keep the original DataSource (a datatable, dataset?) used to populate initially your fields. Then update the related row and use a OracleDataAdapter.

    using(OracleConnection cnn = new OracleConnection(connString)) 
    using (OracleCommand cmd = new OracleCommand("SELECT * FROM TABLE1 WHERE 1=0", cnn))  
    {
         OracleAdapter adp = new OracleDataAdapter();
         adp.SelectCommand = cmd;
         // The OracleDataAdapter will build the required string for the update command
         // and will act on the rows inside the datatable who have the  
         // RowState = RowState.Changed Or Inserted Or Deleted
         adp.Update(yourDataTable);
    }
    

    Keep in mind that this approach is inefficient because it requires two trip to the database. The first to discover your table structure, the second to update the row/s changed. Moreover, for the OracleDataAdapter to prepare the UpdateCommand/InsertCommand/DeleteCommand required, it needs a primary key in your table.

    On the contrary, this is handy if you have many rows to update.

    The last alternative (and probably the fastest) is a StoredProcedure, but in this case you need to go back to my first example and adapt the OracleCommand to use a StoredProcedure, (Add all fields as parameters, change CommandType to CommandType.StoredProcedure and change the text of the command to be the name of the StoredProcedure). Then the StoredProcedure will choose which fields need to be updated.