我有一个SQL语言的表,它的名称是Pagos。
如下所示:
Clave Neto Val1 Val2
-----------------------
01 NULL NULL 5
02 NULL 3 NULL
03 1 NULL NULL
04 NULL NULL NULL我想用SQL Update命令做这样的事情:
Update Table1
Set Neto = 0 WHERE Neto IS NULL,
Val1 = 0 WHERE Val1 IS NULL,
Val2 = 0 WHERE Val2 IS NULL这是可能的吗?
发布于 2014-10-23 08:23:45
如果你的SQL实例支持COALESCE,那么你可以使用:
UPDATE Pagos
SET
Neto = COALESCE(Neto, 0),
Val1 = COALESCE(Val1, 0),
Val2 = COALESCE(Val2, 0);如果x不为空,则COALESCE(x, y, ...)将返回x;否则,如果y不为空,则将返回y,依此类推。
在其他版本的SQL中,有与COALESCE等效的函数。下面是它们的链接:http://www.w3schools.com/sql/sql_isnull.asp
发布于 2014-10-23 08:19:00
假设MS SQL Server:
update Pagos
set
Neto = case when Neto is null then 0 else Neto end,
Val1 = case when Val1 is null then 0 else Val1 end,
Val2 = case when Val2 is null then 0 else Val2 end
where Neto is null or Val1 is null or Val2 is null您可以使用isnull(Neto,0)或coalesce(Neto,0)来代替case when Neto is null then 0 else Neto end,后者通过使用函数来做几乎相同的事情。
实际上并不需要where子句,但是通过排除所有列都不为null的行来节省一些时间。
结果:
Clave Neto Val1 Val2
01 0 0 5
02 0 3 0
03 1 0 0
04 0 0 0https://stackoverflow.com/questions/26519173
复制相似问题