SQL Query无法返回记录

时间:2013-09-09 23:55:32

标签: sql

如果ProjectStatusType.Name不为null,则以下SQL按预期工作。因此,我将使用'未指定'替换空值的case语句。我想要做的是添加一个where语句来显示ProjectStatusType.Name ='Not Specified',但是没有返回数据,尽管数据库中有一个null projectstatustype.name的记录。请指教;什么是另一种方式,或者我如何修复SQL查询?

SELECT PersonResponsible.Name AS TeamLeaderName,
       CASE
           WHEN ProjectStatusType.Name IS NULL THEN 'Not Specified'
           ELSE COALESCE(ProjectStatusType.Name, '')
       END AS ProjectStatusName,
       Project.ProjectTitle AS Title,
       ProjectStatus.DateStatus,
       Project.ProjectId,
       Project.ContactName,
       BusinessDivision.Name AS BusinessUnit,
       BusinessUnit.Name AS WorkSection,
       ProjectSubGroup.Name AS ProjectSubGroupName,
       ProjectGroup.Name AS ProjectGroupName,
       Project.DateRequested
FROM BusinessUnit
INNER JOIN BusinessDivision ON BusinessUnit.BusinessDivisionId = BusinessDivision.BusinessDivisionId
INNER JOIN ProjectCode ON BusinessUnit.BusinessUnitId = ProjectCode.BusinessUnitId
RIGHT OUTER JOIN Project
INNER JOIN ProjectSubGroup ON Project.ProjectSubGroupId = ProjectSubGroup.ProjectSubGroupId
INNER JOIN ProjectGroup ON ProjectSubGroup.ProjectGroupId = ProjectGroup.ProjectGroupId ON ProjectCode.ProjectCodeId = Project.ProjectCodeId
LEFT OUTER JOIN PersonResponsible ON Project.PersonResponsibleId = PersonResponsible.PersonResponsibleId FULL
OUTER JOIN ProjectStatusType
INNER JOIN ProjectStatus ON ProjectStatusType.ProjectStatusTypeId = ProjectStatus.ProjectStatusTypeId
AND ProjectStatus.ProjectStatusId IN
  (SELECT MAX(ProjectStatusId) AS ProjectStatusId
   FROM ProjectStatus
   GROUP BY ProjectId) ON Project.ProjectId = ProjectStatus.ProjectId
WHERE ProjectStatus ProjectStatusType.Name ='Not Specified'

2 个答案:

答案 0 :(得分:0)

两点:

首先,检查null的CASE对于COALESCE表达式来说似乎是多余的。

这应该更简单:

SELECT COALESCE(ProjectStatusType.Name, 'Not Specified') AS ProjectStatusName

其次,与ProjectStatusType.Name(表中的值)进行比较与与ProjectStatusName(您选择的值)的比较不同。

尝试更接近此的WHERE子句:

WHERE ProjectStatusName = 'Not Specified'

答案 1 :(得分:0)

以下是Itzik Ben-Gan关于SQL Server如何处理查询的精彩图表。顺序与我们编写T-SQL的方式不同。

因此rutter的解决方案可能会错过空字符串。

如果我正在做这种类型的业务逻辑,我会编写一个函数,它将同时接受空字符串或空值并返回字符串'unknown'。在查询中调用此函数并按“未知”过滤。

下面的示例创建一个临时表,使用数据加载表,并返回空字符串和转换为调整名称“未指定”的空值。

我希望这会有所帮助。

当查询不按照我认为应该的方式工作时,我总是会参考逻辑处理图表。

祝你好运

约翰

-- 
-- Logical query processing
--

-- From, Where, Group By, Having, Select (expression, distince, top), order by

-- sample table
create table #status
( id int identity(1,1),
  name varchar(50) null
);

-- Sample data
insert into #status values
(''),
(null),
('www.craftydba.com');


-- Return rows with null or empty string
select 
    case when ltrim(name) = '' then 'Not Specified'
    else coalesce(name, 'Not Specified') end as adjusted_named, 
    name
from #status 
where 
  ltrim(name) = '' or 
  coalesce(name, 'Not Specified') = 'Not Specified';