情况是否为空

时间:2015-08-31 14:42:14

标签: sql isnull case-when

我想将PlaceTypeId = 18放在PlaceType.PlaceTypeId列中,如果它为null。我试过这个案例null但它不起作用。难道我做错了什么?

SELECT DoctorsAddress.AddressId, DoctorsAddress.Address, PostalCode.Locality, 
  (CASE WHEN (PlaceType.PlaceTypeId IS NULL) THEN 18 ELSE    
   DoctorsAddress.PlaceTypeId END) AS TipoLocal, 
  (CASE WHEN (placeofvisitquery.placeofvisit IS NULL) THEN '' ELSE
   DoctorEnterpriseDetails.Schedule END) AS Schedule, 
  PostalCode.PostalCode, DoctorsAddress.DoctorId, 
  (CASE WHEN (placeofvisitquery.placeofvisit IS NULL) THEN '' ELSE 'X' END) AS teste
FROM  DoctorsAddress 
 INNER JOIN PlaceType ON DoctorsAddress.PlaceTypeId = PlaceType.PlaceTypeId
 INNER JOIN PostalCode ON DoctorsAddress.PostalCode = PostalCode.PostalCodeId 
 INNER JOIN DoctorEnterpriseDetails ON DoctorsAddress.DoctorId = DoctorEnterpriseDetails.DoctorId 
 LEFT OUTER JOIN DoctorRepresentative ON
   DoctorEnterpriseDetails.EnterpriseId = DoctorRepresentative.EnterpriseId AND 
   DoctorsAddress.DoctorId = DoctorRepresentative.DoctorId AND                       
   DoctorsAddress.AddressId = DoctorRepresentative.placeofvisit 
 LEFT OUTER JOIN placeofvisitquery ON 
   DoctorsAddress.DoctorId = placeofvisitquery.DoctorId AND
   DoctorsAddress.AddressId = placeofvisitquery.placeofvisit
WHERE (DoctorsAddress.DoctorId = @param2) AND (DoctorEnterpriseDetails.EnterpriseId = 26)

1 个答案:

答案 0 :(得分:3)

我认为您的问题是您在INNER JOINDoctorsAddress.PlaceTypeId之间使用了PlaceType.PlaceTypeId,因此会加入with a value中的每一行(并且排除空值)DoctorsAddress 1}}来自PlaceType的每一行。

所以你永远不会得到任何实际拥有PlaceType.PlaceTypeId IS NULL的行。 如果你替换

,你可以拥有这些

INNER JOIN PlaceType ON DoctorsAddress.PlaceTypeId = PlaceType.PlaceTypeId

LEFT OUTER JOIN PlaceType ON DoctorsAddress.PlaceTypeId = PlaceType.PlaceTypeId

然后(如果DoctorsAddress.PlaceTypeId为空),您将拥有DoctorsAddress中选定的行,但PlaceType中找不到相应的行,因为DoctorsAddress.PlaceTypeId IS NULL因为您不能与NULL进行比较,因此PlaceType的每个成员也将是NULL