CASE在SQL Server中不起作用
我试图写if..else条件里面的sql我想从公司名表中获取公司名称,如果他们在companyID中的companyID是NULL print“N / A”con someone help me
SELECT [contactID]
,[customerID]
,(SELECT Label.labelContactType FROM Label WHERE Label.labelContactTypeID = Customer_Contacts.labelContactTypeID)AS Type
,[contactDetails]
,[status]
,[notes]
,CASE WHEN [Customer_Contacts].companyID = NULL THEN 'N/A'
WHEN [Customer_Contacts].companyID <> NULL THEN (SELECT [companyName]
FROM [TaskManagementSystem_DB].[dbo].[Company] WHERE [Company].companyID = [Customer_Contacts].companyID)
END AS Company
FROM [TaskManagementSystem_DB].[dbo].[Customer_Contacts]
WHERE customerID = 24
为什么不为这个查询使用JOIN
:
SELECT cc.[contactID]
,cc.[customerID]
,l.labelContactType AS Type
,cc.[contactDetails]
,cc.[status]
,cc.[notes]
, COALESCE(cp.[companyName], 'N/A') AS Company
FROM [TaskManagementSystem_DB].[dbo].[Customer_Contacts] cc
LEFT JOIN [TaskManagementSystem_DB].[dbo].[Company] cp
on cc.companyID = cp.companyID
LEFT JOIN Label l
on cc.labelContactTypeID = l.labelContactTypeID
WHERE cc.customerID = 24
如果你需要关于连接语法的帮助,这里有一个关于连接的很好的视觉解释
尝试使用'IS NULL'而不是'= NULL','IS NOT NULL'而不是'<> NULL'。
我真的会用JOIN
重写它:它更具可读性,可维护性,并且会更有效率。 你目前正在做的是实现相关的子查询(其中两个,一个用于标签,一个用于公司名称)。 这里是你的查询重写JOIN
和重新格式化的可读性:
SELECT
cust.[contactID]
,cust.[customerID]
,l.labelContactType AS Type
,cust.[contactDetails]
,cust.[status]
,cust.[notes]
,ISNULL(comp.companyName, 'N/A') AS Company
FROM
[TaskManagementSystem_DB].[dbo].[Customer_Contacts] cust
LEFT JOIN
[TaskManagementSystem_DB].[dbo].[Label] l
ON
cust.labelContactTypeID = l.labelContactTypeID
LEFT JOIN
[TaskManagementSystem_DB].[dbo].[Company] comp
ON
cust.companyID = comp.companyID
WHERE
cust.customerID = 24
我会研究JOIN
语法,如果你不熟悉它。