我有一个结合姓和名的SQL查询。但是如果没有名字,那么名字中就有值,那么组合的结果为空
select CompanyContact.FirstName + ' '
+ COALESCE(CompanyContact.LastName, '') AS Name
from bsDocument
LEFT JOIN Contact AS CompanyContact ON CompanyContact.ContactID = bsDocument.DocumentContactID
WHERE bsDocument.SellerID = 3632
AND bsDocument.Module = 'bsContract'
在以下列中,CompanyContact.FirstName的值为null,而CompanyContact.LastName的值为“ Dahal”,但结果显示为null。我该如何解决?
答案 0 :(得分:1)
在FirstName中使用COALESCE
就像姓氏
select COALESCE(CompanyContact.FirstName,'') + ' '
+ COALESCE(CompanyContact.LastName, '') AS Name
from bsDocument
LEFT JOIN Contact AS CompanyContact ON CompanyContact.ContactID = bsDocument.DocumentContactID
WHERE bsDocument.SellerID = 3632
AND bsDocument.Module = 'bsContract'
答案 1 :(得分:1)
使用concat()
select concat(CompanyContact.FirstName,' ',CompanyContact.LastName) AS Name
from bsDocument
LEFT JOIN Contact AS CompanyContact ON CompanyContact.ContactID = bsDocument.DocumentContactID
WHERE bsDocument.SellerID = 3632
AND bsDocument.Module = 'bsContract'
答案 2 :(得分:0)
您可以将stuff()
与字符串串联使用:
select stuff((coalesce(' ' + c.FirstName, '') +
coalesce(' ' + c.LastName, ''),
), 1, 1, '') as Name
from bsDocument d left join
Contact c
on c.ContactID = d.DocumentContactID
where d.SellerID = 3632 and
d.Module = 'bsContract';
这具有很好的属性,只在名字和姓氏之间包含空格 。这种结构很容易扩展为所需的任意多个可空字符串。
答案 3 :(得分:0)
使用CASE表达式:
SELECT
CASE
WHEN NULLIF(CompanyContact.FirstName, '') IS NULL THEN CompanyContact.LastName
ELSE CompanyContact.FirstName + ' ' + CompanyContact.LastName
END AS Name
FROM bsDocument
LEFT JOIN Contact AS CompanyContact ON CompanyContact.ContactID = bsDocument.DocumentContactID
WHERE bsDocument.SellerID = 3632
AND bsDocument.Module = 'bsContract'