简体   繁体   English

if-else条件用于更新SQL Server 2005中存储过程中的表

[英]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? 我可以在存储过程中为此编写什么代码?

You can use a case to control whether you assign a new value or keep the old value. 您可以使用case来控制是分配新值还是保留旧值。

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

Use Case statement in Update clause 在Update子句中使用Case语句

like 喜欢

SQL Statement #6 SQL声明#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 取自SQL SERVER UPDATE

Also you can go with if..else statement 你也可以使用if..else语句

If you would have been in SQL SERVER 2008, you could have avail the flavor of MERGE statement 如果你曾经在SQL SERVER 2008中,你可以利用MERGE语句的风格

Just an example: 举个例子:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM