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

时光总嘲笑我的痴心妄想 提交于 2019-12-12 15:03:03

问题


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?


回答1:


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



回答2:


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




回答3:


Just an example:

IF @a <= 0 
BEGIN
    UPDATE table SET counter = @a, name = 'Minati'
END
ELSE
BEGIN
    UPDATE table SET name = 'Minati'
END



回答4:


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>>


来源:https://stackoverflow.com/questions/1672069/if-else-condition-for-update-a-table-in-a-stored-procedure-in-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!