sql server更新查询中的if条件 [英] if condition in sql server update query
本文介绍了sql server更新查询中的if条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 SQL Server 表,其中有 2 列我想根据发送到存储过程的标志以及新值来更新它们中的任何一个值,例如:
I have a SQL server table in which there are 2 columns that I want to update either of their values according to a flag sent to the stored procedure along with the new value, something like:
UPDATE
table_Name
SET
CASE
WHEN @flag = '1' THEN column_A += @new_value
WHEN @flag = '0' THEN column_B += @new_value
END AS Total
WHERE
ID = @ID
这样做的正确 SQL 服务器代码是什么??
What is the correct SQL server code to do so??
推荐答案
当前的答案很好,应该可以正常工作,但是更简单、更明显且更易于维护的问题有什么问题:
The current answers are fine and should work ok, but what's wrong with the more simple, more obvious, and more maintainable:
IF @flag = 1
UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID;
ELSE
UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID;
尽管这是一个非常简单的查询,但它更易于阅读.
This is much easier to read albeit this is a very simple query.
这是@snyder 提供的一个工作示例:SqlFiddle.
Here's a working example courtesy of @snyder: SqlFiddle.
这篇关于sql server更新查询中的if条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文