1

I have a DataTable object loaded using below code.

DataSet dataset = new DataSet();
adapter.Fill(dataset);
DataTable myDataTable = dataset.Tables[0];

I want to execute this SQL query against that DataTable object:

UPDATE myDataTable 
SET Enabled = 'YES' 
WHERE ID = '123';

I was able to do this using LINQ, but the requirement is to execute SQL queries against the DataTable object.

How can we achieve this?

4
  • Have a look at Edit Rows in a DataTable Commented Oct 5, 2015 at 14:51
  • Thanks huMpty.. I need to dynamically create the query from string input, and there can be multiple columns to update. Any suggestions? Commented Oct 5, 2015 at 15:05
  • so... you need to dynamically generate a SQL statement which will never be seen or used by a SQL database? "No matter how far you have gone on a wrong road, turn back." Commented Oct 5, 2015 at 15:16
  • It is not like that. An example would be, at run time, I need to change the value of the field Enabled to YES for ID 123 in the table. I am storing data in an in-memory datatable object for the time being, and hence wants to see if there is a way to execute SQL queries to update it. Only valid queries will be there. Commented Oct 5, 2015 at 15:19

1 Answer 1

2

The problem is that a DataTable isn't an implementation of SQL, although it understands very limited subset of SQL.

You can use the SELECT filter and then update the rows programmatically:

var myRows = myDataTable.Select("ID = '123'");
foreach (var row in myRows)
{
    row["Enabled"] = "YES";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Russ for your suggestion. The requirement is to execute update queries against the datatable at runtime. The column names are unknown at design time. So I am trying to figure out a way to perform updation at runtime. There can be multiple columns as well to update, and hence cannot use a parameterized version of your solution as well.
I would strongly suggest looking at executing directly against the database, using SqlConnection, SqlCommand and so on. If you don't know the schema at design time, then a DataTable isn't going to be the best option; Never mind that they're almost universally despised!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.