Edit:

Sorry I did not clarify in beginning. CompanyType is smallint, not null and TotalLicenses is int, null

Basically I only want to check that TotalLicenses > 0 if C.CompanyType != 4

I looked at a few reference guides and tutorials, but I couldn't find one that confirmed that I am using CASE WHEN how I intend to in this example.

I am trying to update the "Purchased" column to 1 when Expiration is greater than or equal to Today's date, DemoLicense is equal to 0, and TotalLicenses is greater than 0 if the company type is not 4. If it is 4 it can be 0

update WebCatalog.Published.DemoTracking
set Purchased = 1
from WebCatalog.Published.Company C
    inner join WebCatalog.Published.RCompany RC
        on C.RCompany = RC.Link
    inner join WebCatalog.Published.DemoTracking DT
        on C.PKey = DT.CompanyPKey and DT.Purchased = 0
where RC.Expiration >= Cast(GETDATE() as Date) and RC.DemoLicense = 0
and C.TotalLicenses > 
    Case 
        when C.CompanyType != 4 THEN 0
    END
有帮助吗?

解决方案 3

It is not that much different from the way you described it:

update WebCatalog.Published.DemoTracking
set Purchased = 1
from WebCatalog.Published.Company C
        inner join WebCatalog.Published.RCompany RC
            on C.RCompany = RC.Link
        inner join WebCatalog.Published.DemoTracking DT
            on C.PKey = DT.CompanyPKey and DT.Purchased = 0
 where RC.Expiration >= Cast(GETDATE() as Date) and RC.DemoLicense = 0
 and (C.TotalLicenses > 0 or C.CompanyType = 4)

其他提示

I think you want:

and ( C.CompanyType <> 4 AND C.TotalLicenses > 0 
   OR C.CompanyType = 4 AND C.TotalLicenses >= 0
    )

which can be simplified (under the assumption that these two columns are not nullable) to:

and ( C.TotalLicenses > 0 
   OR C.CompanyType = 4 AND C.TotalLicenses = 0
    )

which, if Company.TotalLicenses can never have negative values, can be further simplified to:

and ( C.TotalLicenses > 0 
   OR C.CompanyType = 4
    )

1st I think the case structure varies between different DBMS. So the following might not apply to you.

2nd When you are not specifiying an Else the case returns NULL. Comparisons with NULL is also NULL, so the row will not be returned. This means that you need a default case.

So you should probably write:

and C.TotalLicenses > 
    Case 
        when C.CompanyType != 4 THEN 0
        else -1
    END
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top