writing an update SQL Query using dataadapter with a muliplier function
I have a windows application using c#. I am using Northwind Products table and I need to update all Unit Prices by the same percentage. I know how to write this in a SELECT query but having trouble with how to write update using multiplication operator and sql parameters and UPDATE query form class to my data access layer and it shows up in the SQL query but I don't have it placed in the right spot because I get null. Can anyone help me with how to write the update string? Here's a snippet of the part of SQL I'm struggling with:
//Update using SQL string
productDataAdapter.UpdateCommand.CommandText =
"UPDATE Products SET " +
"UnitPrice * " + multiplier = "@UnitPrice";
holdParm = new SqlParameter开发者_运维技巧();
holdParm.ParameterName = "@UnitPrice";
holdParm.SourceColumn = "UnitPrice";
productDataAdapter.UpdateCommand.Parameters.Add(holdParm);
//Open connection
productDataAdapter.InsertCommand.Connection.Open();
//usd data adapter to update the Products table
rowCount = productDataAdapter.Update(productsDataSet, "Products");
return rowCount;
How about just execute the query?
decimal factor = 1.1; // for example...
string sql = "UPDATE products set unitPrice = unitprice*" + factor.ToString();
Then use the dbCommand object, set it as follows:
IDbCommand cmd = Database.CreateCommand(sql, CommandType.Text);
cmd.ExecuteReader();
That way you're running the UPDATE and only the update and you know what it does and when it happens. Of course, filter that UPDATE as needed so that you only update what you mean to update.
You are using a DataAdapter in a non-standard way. I'd suggest you consider 2 different approaches:
- Make the update on your in-memory data; in other words: update the rows of the Products table in your data set using C# code. Once the changes are made, you can persist them back to the database with a DataAdapter(or TableAdapter) that is configured in the standard way, so that it just transfer data to and from the in-memory dataset.
- Use TSQL to update the data directly before you load it into the DataSet, or after you save it from the DataSet to the database. In this case you will be using either a Query table adapter or a SqlClient.SqlCommand object.
I can't see any advantage to doing a transformation while you're saving the data back to the database using the DataAdapter. One downside I can see with this approach is that it will be confusing to programmers who are used to using DataAdatpers to simply load and save data.
精彩评论