【发布时间】:2021-09-21 20:38:33
【问题描述】:
我已经建立了一个查询,如果根据我的数据库中的某些字段被更改,在更改日志表中发现更改,我会提取记录。如果不进行更改,则不存在任何记录。我已经建立了我的查询,它可以很好地给我想要的东西,但问题是,当我将其缩小到一个日期范围时,如果更改日志中没有要检查的记录,我什么也得不到。有没有办法在 where 语句中执行某种“如果存在”来检查日期,如果记录不存在,仍然允许返回结果,因为我在 select 语句中编码了结果文本?这是我的代码:
Declare @StartDate as date
Declare @EndDate as date
Set @StartDate = '9/20/2021'
Set @EndDate = '10/1/2021'
Select DISTINCT n.ID, n.FULL_NAME, n.Company, n.Status, n.Email,
Case
when Coalesce(CLDP.CurrentValue, 'No Update Found') <> 'No Update Found' then CLDP.CurrentValue
When Coalesce(CLDP.CurrentValue, 'No Update Found') = 'No Update Found' and b.PROFESSION <> '' then b.PROFESSION
when Coalesce(CLDP.CurrentValue, 'No Update Found') = 'No Update Found' and b.PROFESSION = '' then 'No Update Found'
end as ProfessionUpdate,
Case
when Coalesce(CLDE.CurrentValue, 'No Update Found') <> 'No Update Found' then CLDE.CurrentValue
When Coalesce(CLDE.CurrentValue, 'No Update Found') = 'No Update Found' and b.ETHNICITY <> '' then b.ETHNICITY
when Coalesce(CLDE.CurrentValue, 'No Update Found') = 'No Update Found' and b.ETHNICITY = '' then 'No Update Found'
end as EthnicityUpdate,
Case
when Coalesce(CLDG.CurrentValue, 'No Update Found') <> 'No Update Found' then CLDG.CurrentValue
When Coalesce(CLDG.CurrentValue, 'No Update Found') = 'No Update Found' and b.Gender <> '' then b.Gender
when Coalesce(CLDG.CurrentValue, 'No Update Found') = 'No Update Found' and b.Gender = '' then 'No Update Found'
end as GenderUpdate,
Case
when Coalesce(nl.LOG_TEXT, 'No Update Found') <> 'No Update Found' then nl.Log_Text
When Coalesce(nl.LOG_TEXT, 'No Update Found') = 'No Update Found' and Cast(n.BIRTH_DATE as varchar) <> '' then Cast(n.BIRTH_DATE as VarChar)
when Coalesce(nl.LOG_TEXT, 'No Update Found') = 'No Update Found' and Cast(n.BIRTH_DATE as varchar) = '' then 'No Update Found'
end as BirthDateUpdate
from Customer as n inner join
Members as b on b.ID = n.ID left join
Profession as CLDP on n.ID = CLDP.ID left join
Ethnicity as CLDE on n.ID = CLDE.ID Left Join
Gender as CLDG on n.ID = CLDG.ID Left Join
BirthDate as nl on nl.ID = n.ID
Where n.ID in ('12345', '67890') and
cldp.createdon between @startDate and @endDate and
clde.createdon between @startdate and @enddate and
cldg.createdon between @startdate and @enddate and
nl.date_time between @StartDate and @EndDate
【问题讨论】:
-
你可以检查日期是否为空
-
那么在 were 语句中运行一个合并还是一个 IS NULL?在我今天运行的测试的情况下,查询结果没有数据,因为从 4 个表中提取的 3 个表中根本没有问题 ID。
标签: sql sql-server-2016