簡體   English   中英

使用SQL Server在存儲過程中比較兩個日期時間值?

[英]Compare two datetime values in a stored procedure using SQL Server?

在存儲過程的SELECT語句中,我必須獲取最大datetime值。

((SELECT MAX(MyDateTime) 
  FROM MyTable 
  WHERE MyId = MM.MyId)) as RecentDateTime,

這可行。 我在SQL Server Management Studio網格中看到帶有datetime值的新列。

但是,我需要將此值與另一個datetime值進行比較,以查看它們是否相等。 我在SELECT語句中收到以下語句的語法錯誤

((SELECT MAX(MyDateTime) 
  FROM MyTable 
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,  

要么:

@RecentDateTime = ((SELECT MAX(MyDateTime) 
                    FROM MyTable 
                    WHERE MyId = MM.MyId) = MM.MyDateTime)

如果我可以將比較結果存儲到變量中,則可以采用該值並將其與另一個值進行比較。

不知道為什么我不斷收到語法錯誤或如何解決此錯誤。 任何幫助都會受到新手的贊賞。

我想你想要類似的東西

  DECLARE @maxDate DATETIME
  Select @maxDate = MAX(MyDateTime) from MyTable where MyId = testIdValue

現在,您可以使用=< >運算符與任何其他日期值進行比較

相關子查詢如何?

select 
     t.MyId
    ,t.MyDateTime
    ,RecentDateTime = (select max(t2.MyDateTime) from MyTable t2 where t2.MyId = t.MyId)
from
    MyTable t

或使用派生表...

select 
    t.MyId
    ,t.MyDateTime
    ,RecentDateTime = t2.DT
from
    MyTable t
left join
    (select t2.MyId, max(t2.MyDateTime) DT from MyTable t2 group by t2.MyId) t2 on t2.MyId = t.MyId

然后,如果您只想要它們不匹配的那些,則可以將其包裝在CTE中...

;with cte as(
    select 
        t.MyId
        ,t.MyDateTime
        ,RecentDateTime = t2.DT
    from
        MyTable t
    left join
        (select t2.MyId, max(t2.MyDateTime) DT from MyTable t2 group by t2.MyId) t2 on t2.MyId = t.MyId)

select * 
from cte
where MyDateTime <> RecentDateTime

不確定其他日期還是比較結果,但是如果您只想比較兩個日期的結果,請嘗試:

case when (SELECT MAX(MyDateTime)  
          FROM MyTable  
          WHERE MyId = MM.MyId) = MM.MyDateTime 
then 1 else 0 end as isMaxMyDT_eq_myDT

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM