左联接返回null时创建默认值

时间:2018-11-16 07:14:15

标签: sql-server left-join isnull

我有这样的查询

select * 
from Users u left join(
                       select ContactInformationId, 
                              Address, 
                              City, 
                              StateProvince, 
                              CountryId, 
                              ZipCode, 
                              PrimaryContactNumber, 
                              Fax, 
                              MobileNumber 
                       from ContactInformation
                     ) c on u.ContactInformationId = c.ContactInformationId 
left join  (
            select ISNULL(MerchantId, @MerchantId) as MerchantId, 
                   ISNULL(MerchantName, @MerchantName) as MerchantName, 
                   ISNULL(MerchantEmail, @MerchantEmail) as MerchantEmail, 
                   ISNULL(ContactInformationId, @ContactInformationId) as ContactInformationId 
            from Merchants
           ) m on c.ContactInformationId = m.ContactInformationId 
left join (
           select IsNull(MidId, 0) as MidId, 
                  IsNull(MidName, '') as MidName, 
                  IsNull(MerchantId, 0) as MerchantId, 
                  IsNull(Param_2, '') as Param_2, 
                  IsNull(Param_6, '') as Param_6 
           from Mids
          ) MID on m.MerchantId = MID.MerchantId 
where u.FirstName = '' and u.LastName = '' or u.MiddleName = ''

enter image description here

以及类似的结果。我想问的是,有没有办法为这些NULL列设置默认值?

1 个答案:

答案 0 :(得分:4)

您可以在选择查询中使用ISNULL()

例如;我将MerchantId为null时设置为0,将MidName为null时设置为空字符串

ISNULL(MerchantId, 0)
ISNULL(MidName, '')

在主查询中执行此操作。

例如;

select ISNULL(m.MerchantId, 0), ISNULL(Mid.MidName, '') 
from Users u