views:

125

answers:

4

I want to update some data in a specified case, else these fields are not to be updated.

What can i write code in a stored procedure for this?

A: 

Just an example:

IF @a <= 0 
BEGIN
    UPDATE table SET counter = @a, name = 'Minati'
END
ELSE
BEGIN
    UPDATE table SET name = 'Minati'
END
Faruz
+2  A: 

You can use a case to control whether you assign a new value or keep the old value.

update <sometable>
set field = case when <condition> then <newvalue> else field end
where <condition>

Example:

update questions
set reply = case when @input is not null then @input else reply end
where answer = 42
Guffa
ISNULL(@input, field) ?
devio
@devio: Yes, for the specific case where the condition is a check for null, the isnull function can be used instead of a case, but I wanted to show the case as it can be used for any kind of condition. :)
Guffa
@Guffa: +1 for this being my preferred solution as well. Maybe you should edit your answer and change "@input is not null" to "<some condition applies>" to make clear that field update will occur if some condition applies, independent of @input.
Thorsten Dittmar
@Thorsten: Good point, I edited the anwer to have a pseudo code that shows the principle and an example.
Guffa
+1  A: 

May be you can build the condition in the update command and easily run more than one update with the diferent conditions. It may not be the most elegant way but it is prety eficient. It depends of your needs.

UPDATE table SET field=value WHERE <<condition>>
UPDATE table SET field=value2 WHERE <<condition2>>
j.a.estevan
+1  A: 

Use Case statement in Update clause

like

SQL Statement #6

UPDATE titles
       SET price =
                 CASE
                   WHEN (price < 5.0 AND ytd_sales > 999.99)
                                   THEN price * 1.25
                   WHEN (price < 5.0 AND ytd_sales < 1000.00)
                                   THEN price * 1.15
                   WHEN (price > 4.99 AND ytd_sales > 999.99)
                                   THEN price * 1.2
                   ELSE price
                 END

Taken from SQL SERVER UPDATE

Also you can go with if..else statement

If you would have been in SQL SERVER 2008, you could have avail the flavor of MERGE statement

priyanka.sarkar