SQL:仅当该值为空时如何更新列上的值?
我有一个 SQL 问题,这对某些人来说可能很基本,但让我感到困惑。
以下是表“Person”的列名称示例: PersonalID、FirstName、LastName、Car、HairColour、FavDrink、FavFood
假设我输入行:
121312,雷纳,彼得森,BMW123d,棕色,NULL,NULL
现在我想更新此人的值,但前提是新值不为空,更新:
121312,雷娜,彼得森,NULL,金发女郎,芬达,NULL
新行需要是:
121312,雷娜,彼得森,BMW123d,金发女郎,芬达,NULL
所以我在想以下内容:
更新人员(个人 ID、名字、姓氏、汽车、头发颜色、 FavDrink、FavFood) set Car = @Car(其中 @Car 不为空)、HairColour = @HairColour(其中@HairColour...)...等等
我唯一担心的是我无法在查询末尾对所有条件进行分组,因为它将要求所有值具有相同的条件。如果@HairColour 不为 Null,我不能执行类似更新 HairColour 的操作吗
I have an SQL question which may be basic to some but is confusing me.
Here is an example of column names for a table 'Person':
PersonalID, FirstName, LastName, Car, HairColour, FavDrink, FavFood
Let's say that I input the row:
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, Rayna, Pieterson, NULL, Blonde, Fanta, NULL
The new row needs to be:
121312, Rayna, Pieterson, BMW123d, Blonde, Fanta, NULL
So I was thinking something along the lines of:
Update Person(PersonalID, FirstName, LastName, Car, HairColour,
FavDrink, FavFood) set Car = @Car (where @Car is not null), HairColour
= @HairColour (where @HairColour...)... etc.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为此,我使用了合并:
http://msdn.microsoft.com/en-us/library/ms190349.aspx
Id use coalesce for this:
http://msdn.microsoft.com/en-us/library/ms190349.aspx
以下内容应该有效:
它使用 SQL Server ISNULL 函数,该函数返回
The following should work:
It uses the SQL Server ISNULL function, which returns
您可以使用
isnull
函数:You can use the
isnull
function:将列设置为等于其自身,并在其周围设置 isnull 将其设置为您的参数。
Set the column equal to itself with an isnull round it setting it to your parameter.