View Single Post
Join Date: May 2004
Posts: 71
Reputation: gusano79 is on a distinguished road 
Solved Threads: 4
gusano79 gusano79 is offline Offline
Junior Poster in Training

Re: Updating SQL database, Please help

 
0
  #7
Sep 10th, 2008
Originally Posted by markyjj View Post
An unhandled exception of type 'System.InvalidOperationException' occurred in system.data.dll

Additional information: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
Ah, yes. The command builder also requires that your SELECT statement return a primary key or unique index.

If your table has either of those, you may be able to get away with simply adding the appropriate column(s) to the SELECT statement.

If not, you'll have to write the update command yourself. Here's what it might look like:

  1. using(SqlConnection connection = new SqlConnection("<connection string>"))
  2. {
  3. SqlDataAdapter adapter = new SqlDataAdapter(
  4. "SELECT SomeField, SomeOtherField FROM Table"
  5. );
  6.  
  7. adapter.UpdateCommand = new SqlCommand(
  8. "UPDATE Table SET SomeField = @SomeField WHERE TheKey = @TheKey"
  9. );
  10.  
  11. adapter.UpdateCommand.Parameters.Add(
  12. "@TheKey", SqlDbType.Int).SourceColumn = "TheKey";
  13.  
  14. adapter.UpdateCommand.Parameters.Add(
  15. "@SomeField", SqlDbType.Binary).SourceColumn = "SomeField";
  16.  
  17. DataTable table = new DataTable();
  18.  
  19. connection.Open();
  20.  
  21. adapter.Fill(table);
  22.  
  23. foreach(DataRow row in table.Rows)
  24. {
  25. row["SomeField"] = (int)row["SomeOtherField"] == 42;
  26. }
  27.  
  28. adapter.Update(table);
  29. }
--smg
Reply With Quote