Hi Suzy:
suzy said:
hello,
i have a table with 10 fields. i want to write an update stored procedures
so i can update any number of fields in the table, but i don't want to write
a seperate sp for every combination of parameters.
is there a way around this problem? and do i need to do anything special
when calling my sp from my c# code?
thanks.
You'll have two problems to address that I can think of. 1) If the
parameter is expected, you'll have to pass it in or give it a default value.
2) You'll only want to Update fields based on parameters that have changed.
so if @FirstValue is what you specified as the default, you don't want to
overwrite the 'good' value with the default.
Dealing with the first problem is pretty easy, just give the params default
values on the server side.
http://www.knowdotnet.com/articles/defaultparameters.html
You can also specify the sourceColumn in the Parameter constructor
http://msdn.microsoft.com/library/d...systemdatasqlclientsqlparameterclasstopic.asp
Which will give you the defaults that you need and make sure everythign is
mapped correctly. For simplicity, this is probably all you really need to
do , not write code for every scenario of the proc.
However, I came across a very interesting approach in Rockford Lhotka's
Business Objects bookl. If you pull over your data and model your objects
according to the data in the db, store the objects in a collection, then
just map each of Param values to its respective field in the object. This
way, each object you have will have the exact values taht were in the DB
originally. You can change any of the fields but the ones you didn't change
will still match the database values. Then you can pass in the object to
your function which builds the parameters and calls the proc. in doing so,
you'll do away with the problem of parameters and you won't have to check
your default values before calling the Set in your proc b/c the 'default'
value will in fact the the value that's already in the DB.
For instance, I have a Table with ID, FirstName, LastName and DOB
I create a Person Object with Four Properties adn then call DataAdapter.Fill
and grab each of the four fields in a DataTable. now, each time I do
anything, update, insert delete etc, I can create an instance of the object
and set it's values according the the datatable. So, the only things in my
collection will be records that have changed. So, now I pass the
collection to a function that calls the update and I can walk through it
specifying the parameters which will map directly to the given object in the
collection and call executenonquery after I set them.
This is the 'short summary' of the concept and doesn't do Lhotka's idea
justice, but you may want to check out his book if you have some time b/c
it's a really cool approach.
HTH,
Bill