I need to write a stored procedure to update one of a set of similar columns. The columns are named ‘UserField1’, ‘UserField2’ etc. I was hoping to pass a parameter to the SPROC which would set the column to be updated. However, I can’t seem to get the code correct. Here’s a simplified example of what I tried (which gets me an ‘Incorrect syntax’ message):
create procedure UpdateUserField
(@UserFieldNumber int, @UserFieldNewValue int)
as
update MyTable set
case @UserFieldNumber
when 1 then UserField1
when 2 then UserField2
end
= @UserFieldNewValue
What about using a number of IF’s?
Alternatively you can build dynamic SQL in an exec
Beware SQL Injection if you do this though, with ints you won’t have a problem, anything else you may need to consider risks.