我正在处理一些继承的代码,并且在其中遇到SQL查询问题。查询如下。
Select distinct
g.scriptid,
g.procedurename,
h.parameters,
g.scriptname,
h.usercode,
h.facility,
h.recid,
cast((cast(recid as varchar) + '.' + Right('0000' + cast(scriptgennum as varchar), 4)) as decimal(10,4)) as 'scriptrecid',
scriptgennum+1 as 'scriptgennum',
h.generated,
h.runinterval,
case
when runinterval = 'M' then dateadd(month,1,convert(varchar(10),h.nextrundate,120))
when runinterval = 'Q' then dateadd(month,3,convert(varchar(10),h.nextrundate,120))
when runinterval = 'W' then dateadd(week,1,convert(varchar(10),h.nextrundate,120))
when runinterval = '0' then NULL end as 'nextrundate',
convert(varchar(10),getdate(),120) as currentrundate,
scripttype
from PATIENTLETTERS_SCRIPTHIST h join PATIENTLETTERS_SCRIPTS g on
g.scriptid = h.scriptid where
h.status = 'Y'
and (([runinterval] = 'M'
and (convert(varchar(10),nextrundate,120) = convert(varchar(10),getdate(),120)
and datepart(day,getdate()) = 5
and (datediff(month,convert(varchar(10),h.lastrundate,120),convert(varchar(10),getdate(),120)) = 1)
or lastrundate is null))
or ([runinterval] = 'Q'
and (convert(varchar(10),nextrundate,120) = convert(varchar(10),getdate(),120)
and datepart(weekday,getdate()) = 0
and (datediff(month,convert(varchar(10),h.lastrundate,120),convert(varchar(10),getdate(),120)) = 3)
or lastrundate is null))
or ([runinterval] = 'W'
and (convert(varchar(10),nextrundate,120) = convert(varchar(10),getdate(),120)
and datepart(day,getdate()) = 5
and (datediff(week,convert(varchar(10),h.lastrundate,120),convert(varchar(10),getdate(),120)) = 1)
or lastrundate is null))
or ([runinterval] = 'O'
and (convert(varchar(10),nextrundate,120) = convert(varchar(10),getdate(),120)
and (datepart(weekday,getdate()) = 0))
or lastrundate is null))
我知道它正在尝试选择PATIENTLETTERS_SCRIPTHIST
和PATIENTLETTERS_SCRIPTS
中列出的特定列。让我困惑的查询部分是这样的行:
and (([runinterval] = 'M'
and (convert(varchar(10),nextrundate,120) = convert(varchar(10),getdate(),120)
and datepart(day,getdate()) = 5
and (datediff(month,convert(varchar(10),h.lastrundate,120),convert(varchar(10),getdate(),120)) = 1)
如果有人可以解释这些线路实际上在做什么,我将非常感谢任何帮助。我可以看到它想确保运行间隔是'M',并且看起来它试图将当前日期与第4行中存储在数据库中的那天匹配,但是第2行和第3行是仍然是一个完整的谜。
答案 0 :(得分:2)
答案 1 :(得分:1)
此代码正在查找具有runinterval = 'M'
line 1 - [runinterval] = 'M'
且nextrundate
等于当前日期(getdate()
),日期为converted,格式相同的varchar。
line 2 - and (convert(varchar(10),nextrundate,120) = convert(varchar(10),getdate(),120)
并且当前日期的日期等于5.意思是日期必须是6月5日,7月5日等等。
line 3 - and datepart(day,getdate()) = 5
并且lastrundate
的月份与当前日期(getdate()
)之间的差异等于1
line 4 - (datediff(month,convert(varchar(10),h.lastrundate,120),convert(varchar(10),getdate(),120)) = 1)
答案 2 :(得分:1)
第二行使用样式120(More details here)将nextrundate
和当前日期转换为'YYYY-MM-DD'格式,然后检查它们是否相同,因此只有{{{{ 1}}今天就是。
第三行只是检查今天是该月的第5天。例如:
nextrundate
返回5.