2

I have a table with a non-null field I wish to populate from another table. Trouble is the query into the other table may return null. How do I get a value (0 will do) when the query returns null? My query is:

update Packages
    set PackageTypeId = (SELECT TOP 1 PackageTypeId
                         FROM PackageTypes
                         WHERE Packages.PackageTypeName = PackageTypes.Name
                         ORDER BY PackageTypeId ASC)

I tried using coalesce, but it still fails:

update Packages
     set PackageTypeId = (SELECT TOP 1 coalesce(PackageTypeId, 0) as id
                          FROM PackageTypes
                          WHERE Packages.PackageTypeName = PackageTypes.Name
                          ORDER BY PackageTypeId ASC)

Any ideas?

2 Answers 2

6
update Packages 
set PackageTypeId = coalesce((SELECT TOP 1 PackageTypeId FROM PackageTypes 
                              WHERE Packages.PackageTypeName = PackageTypes.Name 
                              ORDER BY PackageTypeId ASC), 0)
Sign up to request clarification or add additional context in comments.

1 Comment

That makes bucket loads of sense. Thanks.
2

I recommend UPDATE FROM statement combined with ISNULL function:

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

Note: Subquery return smallest PackageTypeId for each Name in PackageType

4 Comments

but the order by and top 1 part is lost
order by and top 1 is not necessary in this case - mathing rows is done by join. BTW. I'm not sure, but this form should be faster than finding top 1 row for each ID.
the order by and top 1 suggest that there are multiple PackageTypeId per PackageTypeName. the original query chooses the one with the least ID, yours not.
You are right! I've modified query above according to this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.