Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-else condition for update a table in a stored procedure in SQL Server 2005

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

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

like image 954
Minati Behera Avatar asked Nov 28 '22 11:11

Minati Behera


2 Answers

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
like image 151
Guffa Avatar answered Dec 04 '22 07:12

Guffa


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

like image 20
priyanka.sarkar Avatar answered Dec 04 '22 09:12

priyanka.sarkar