I have a question about updating table through t-sql. The client may want to update one column in row and leave the rest unchanged or he may want to update multiple columns. So I have two solutions:
-
Create one sp and update the whole table. The client has to provide all the parameters even if he wants to update a single column in a row so if he pass (which he has to) null for the parameters that he doesn’t have… well the original values will be lost. As a workaround I can use conditions to check for null parameters (different commands based on condition). However there is another issue, how can I recognize an int parameter? I mean suppose we have an int column that can have any integer values including zero so what should the client send to sp for saying “this is not a new value leave the value as is”.
-
Create one sp per column. the client will use the appropriate sp to update a single column in a row so if he wants to update multiple columns he can call each related sp one after another and pass the two parameters which would be the row(s) id and the new value. What if I have a table with 25 updatable columns? Oh man! 25 update sp just for a single table!
Do I have to create an update sp per each table column? Or create one sp that takes all the row parameters and updates the whole table? What is the de-facto standard for writing update procedures?
EDIT1: i’m using sql server 2005 with front-end c# and asp.net app but i want to do it in t-sql.
If you truly must do this in T-SQL, then the only viable approach to me would be to use dynamic SQL. If you consider this, you must first read (and understand!) Erland Sommarskogs excellent essay The curse and blessings of dynamic SQL – absolute must-read!
Basically, you’d have a single stored proc that takes your 25 parameters. Each of those can be NULL if it doesn’t need to be updated.
Inside your stored proc, you basically build up your T-SQL
UPDATEstatement based on which parameters are non-NULL, and in the end, you execute that statement.This gives you one procedure, but that procedure will be quite messy to look at.