問題描述
我正在閱讀前任編寫的腳本.
I was going through a script written by a predecessor.
誰能給我解釋一下為什么會有這個說法
Can someone explain to me why would this statement
--- CreatedDateTime is a datetime column in SALES_ORDER table.
SELECT * FROM SALES_ORDER
WHERE GETDATE() - CreatedDateTime < 1
返回與
SELECT * FROM SALES_ORDER
WHERE DateDiff(hh,CreatedDateTime, GetDate()) < 24
推薦答案
從 DATETIME 中減去 數(shù)字 記錄在 此處:還可以從日期中減去一個數(shù)字,以天為單位."
Subtraction of a number from a DATETIME is documented here: "Can also subtract a number, in days, from a date."
declare @Now as DateTime = GetDate();
declare @OneWeekAgo as SQL_Variant = @Now - 7;
select @Now as [Now], @OneWeekAgo as [Delta], SQL_Variant_Property( @OneWeekAgo, 'BaseType' ) as [Data Type];
在使用帶有日期和時間數(shù)據(jù)的運(yùn)算符類型:要對所有日期和時間數(shù)據(jù)類型進(jìn)行加減運(yùn)算,請使用 DATEADD 和 DATEDIFF."
Under Using Operators with Date and Time Data Types: "To add and subtract for all date and time data types, use DATEADD and DATEDIFF."
在可能違反最小驚訝原則的情況下,我們看到了以下奇怪的結(jié)果:
In a possible violation of the Principle of Least Astonishment we see the following curious result:
declare @Now as DateTime = GetDate();
declare @Then as DateTime = '17760704';
declare @Delta as SQL_Variant = @Now - @Then;
select @Now as [Now], @Then as [Then], @Delta as [Delta],
SQL_Variant_Property( @Delta, 'BaseType' ) as [Data Type],
Cast( @Delta as Int ) as [Days];
<小時>
Aaron Bertrand 條款:所提供的信息未經(jīng) Aaron Bertrand 批準(zhǔn).此外,作者未能指出它在任何給定環(huán)境中可能不適用或不太理想的所有可能方式,無論多么晦澀或人為.作者還犯下了未能明確引用 Aaron Bertrand 的至少三 (3) 篇博文和規(guī)范答案的主要和/或順序錯誤.因此,它對整個社區(qū)沒有任何好處,應(yīng)該立即永久地將作者從所有 StackExchange 站點(diǎn)中驅(qū)逐出去,并且應(yīng)該從中刪除作者提供的任何內(nèi)容.Microsoft 出色的文檔在多大程度上導(dǎo)致了任何(誤解)理解,這無關(guān)緊要.
Aaron Bertrand Clause: The information provided is unapproved by Aaron Bertrand. Additionally, the author has failed to indicate all possible ways in which it may be inapplicable or less-than-optimal in any given environment, no matter how obscure or contrived. The author has also made the cardinal and/or ordinal sin of failing to explicitly reference a minimum of three (3) of Aaron Bertrand's blog posts and canonical answers. Thus it offers no benefit to the community at large and the author should be immediately and permanently banished from all StackExchange sites and any content provided by the author should be removed therefrom. It matters not a whit the extent to which Microsoft's splendid documentation may have contributed to any (mis)understanding.
這篇關(guān)于t-sql中兩個日期相減的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!