SQL: How can I update a value on a column only if that value is null?(SQL:只有当该值为空时,如何才能更新列上的值?)
问题描述
我有一个 SQL 问题,对某些人来说可能很基础,但让我感到困惑.
I have an SQL question which may be basic to some but is confusing me.
以下是表Person"的列名示例:PersonalID、FirstName、LastName、Car、HairColour、FavDrink、FavFood
Here is an example of column names for a table 'Person': PersonalID, FirstName, LastName, Car, HairColour, FavDrink, FavFood
假设我输入了行:
121312、Rayna、Pieterson、BMW123d、布朗、NULL、NULL
121312, Rayna, Pieterson, BMW123d, Brown, NULL, NULL
现在我想更新这个人的值,但前提是新值不为空,更新:
Now I want to update the values for this person, but only if the new value is not null, Update:
121312,蕾娜,皮特森,NULL,金发,芬达,NULL
121312, Rayna, Pieterson, NULL, Blonde, Fanta, NULL
新行需要是:
121312、蕾娜、皮特森、BMW123d、金发、芬达、NULL
121312, Rayna, Pieterson, BMW123d, Blonde, Fanta, NULL
所以我的想法是这样的:
So I was thinking something along the lines of:
更新人员(PersonalID、FirstName、LastName、Car、HairColour、FavDrink, FavFood) 设置 Car = @Car (@Car 不为空), HairColour= @HairColour(@HairColour...)...等
Update Person(PersonalID, FirstName, LastName, Car, HairColour, FavDrink, FavFood) set Car = @Car (where @Car is not null), HairColour = @HairColour (where @HairColour...)... etc.
我唯一担心的是我无法在查询结束时对所有条件进行分组,因为它要求所有值都具有相同的条件.如果@HairColour 不是 Null,我不能做类似更新 HairColour 的事情
My only concern is that I can't group all the conditions at the end of the query because it will require all the values to have the same condition. Can't i do something like Update HairColour if @HairColour is not Null
推荐答案
我为此使用了 coalesce:http://msdn.microsoft.com/en-us/library/ms190349.aspx
Id use coalesce for this: http://msdn.microsoft.com/en-us/library/ms190349.aspx
update Person
set Car = coalesce(@Car, Car), HairColour = coalesce(@HairColour, HairColour)
这篇关于SQL:只有当该值为空时,如何才能更新列上的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL:只有当该值为空时,如何才能更新列上的值?
基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01