我有一个非空字段的表,我希望从另一个表填充。麻烦是查询到其他表可能会返回null。当查询返回null时,如何获取值(0将执行)? 我的疑问是:
update Packages
set PackageTypeId = (SELECT TOP 1 PackageTypeId
FROM PackageTypes
WHERE Packages.PackageTypeName = PackageTypes.Name
ORDER BY PackageTypeId ASC)
我尝试使用coalesce,但它仍然失败:
update Packages
set PackageTypeId = (SELECT TOP 1 coalesce(PackageTypeId, 0) as id
FROM PackageTypes
WHERE Packages.PackageTypeName = PackageTypes.Name
ORDER BY PackageTypeId ASC)
有什么想法吗?
答案 0 :(得分:6)
update Packages
set PackageTypeId = coalesce((SELECT TOP 1 PackageTypeId FROM PackageTypes
WHERE Packages.PackageTypeName = PackageTypes.Name
ORDER BY PackageTypeId ASC), 0)
答案 1 :(得分:2)
我建议将UPDATE FROM语句与ISNULL函数结合使用:
UPDATE
Packages
SET
Packages.PackageTypeId = ISNULL(PackageTypes.PackageTypeId,0)
FROM
Packages
INNER JOIN
(
SELECT
PackageTypeId,
Name
FROM
(
SELECT
PackageTypeId,
Name,
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY PackageTypeId ASC) R
FROM
PackageTypes
) X
WHERE
R = 1
) PackageTypes
ON
Packages.PackageTypeName = PackageTypes.Name
注意:子查询为PackageType中的每个名称返回最小的PackageTypeId