Necesita un ejemplo de proceso almacenado de actualización condicional en el servidor SQL

I am just at starting levels in DB usage and have 2 basic questions

  1. I have a generic UPDATE stored proc which updates all columns of a table.

But i need to make it conditional wherein it does not SET when the parameter is NULL.

Usage: I want to use this as a single SP to UPDATE any subset of columns, the caller from C# will fill in corresponding parameter values and leave other parameters NULL.

2

In case of , "UPDATE selected records" do i need to use locking inside stored proc ?

Why ? Isn't the operation in itself locked and transactional ?

I find the same question come up when i need to UPDATE selected(condition) records and then Return updated records.

preguntado el 09 de enero de 11 a las 07:01

If NULL = "Don't update", How would you handle the situation when you want to set a column to NULL that previously held a value? -

@Ronnis Valid point. I dont know how to handle that, does anyone ? Coming back to original goal, I didnt want to write so many stored-procs like one for each column update. So wanted a generic solution, which can be anything (NULL thing i talked about is just an example i had in mind) -

2 Respuestas

UPDATE table SET a = case when @a is null then a else @a end WHERE id = @id

OR

EXEC 'update table set ' + @update + ' where id = ' + @id

OR

Conditionally update a column at a time


First option to me would usually be preferrable as it is usually efficient enough and you do not need to worry about string escaping

Respondido el 09 de enero de 11 a las 14:01

Coming back to original goal, I didnt want to write so many stored-procs like one for each column update. So wanted any generic standard solution. Can you help on that as well ? - Munish Goyal

@Munish can you improve your question to include psuedo-code of your desired functionality. These solutions work fine, generically. However you can not take a generic (params) style parameter for procs so a fair bit of coding is required. Unless you write a proc that writes a proc, but that is way too fancy - Sam Saffron

If I have understood the question properly, Why can't you build a query on the fly from sql server SP, and use sp_sqlexecute. So when you build query you can ensure only columns that have value has got updated.

¿Responde esto a tu pregunta?

Respondido el 09 de enero de 11 a las 10:01

Can you elaborate on how to generate on the fly queries. Useful info. But we mostly try to go by stored procs only, dont know how on the fly thing will work out. - Munish Goyal

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.