电子邮件查询条件的结果

时间:2017-11-17 17:44:09

标签: sql sql-server sql-server-2008

我有一个获取2个最新日期时间值的查询。如果值大于5分钟,我需要获取日期时间和电子邮件的差异。我已经使用3个表完成了它,但我想在一个查询中完成它。

SELECT DATEDIFF(minute, T1, T2) + 10 As DIFF
FROM
(SELECT TOP 1 T1.DateAndTime As T1,  T2.DateAndTime AS T2 

FROM [WIMS_SQL].[dbo].[FloatTable] as T1


Inner Join [WIMS_SQL].[dbo].[FloatTable] as T2

On T1.DateAndTime > T2.DateAndTime 

Order By  T2.DateAndTime Desc)

IF DIFF > 5 "EMAIL FUNCTION"  

我确信这比使用

更好

1 个答案:

答案 0 :(得分:1)

这是CTE的逻辑。

declare @minutes int

;with cte as(
    select top 2 DateAndTime
    from [WIMS_SQL].[dbo].[FloatTable]
    order by DateAndTime desc)


select 
    @minutes = datediff(minute, max(DateAndTime), min(DateAndTime)) + 10
from cte

if (@minutes > 5)    
begin
    exec msdb..sp_send_dbmail
         @profile_name = 'Profile Name You Set Up'
        ,@recipients = 'someone@domain.com'
        ,@subject = 'some subject'
end

<强> ONLINE DEMO

此方法将阻止您制作具有该连接条件的笛卡尔积,并且应该更快。