EOMONTH (Transact-SQL)

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體Azure Synapse AnalyticsAnalytics Platform System (PDW)

此函式會以選擇性位移,傳回包含指定日期的當月最後一天。

提示

您可以使用 DATETRUNC 來計算月份的開始時間。

Transact-SQL 語法慣例

Syntax

EOMONTH ( start_date [ , month_to_add ] )

注意

若要檢視 SQL Server 2014 (12.x) 和舊版的 Transact-SQL 語法,請參閱 舊版檔

引數

start_date

日期運算式,指定要傳回當月最後一天的日期。

month_to_add

選擇性整數運算式,指定要新增至 start_date 的月數。

如果 month_to_add 引數具有值,則 EOMONTH 會將指定月數新增至 start_date,然後傳回當月最後一天作為結果日期。 如果這個加法溢位有效的日期範圍,則 EOMONTH 引發錯誤。

傳回類型

date

備註

EOMONTH 式可以遠端至執行 SQL Server 2012 (11.x) 和更新版本的實例。 SQL Server 2012 (11.x) 之前的版本無法遠端連線到實例。

範例

A. 具明確日期時間類型的 EOMONTH

DECLARE @date DATETIME = '12/1/2024';

SELECT EOMONTH(@date) AS Result;
GO

以下為結果集。

Result
------------
2024-12-31

B. 具有字串參數及明確轉換的 EOMONTH

DECLARE @date VARCHAR(255) = '12/1/2024';

SELECT EOMONTH(@date) AS Result;
GO

以下為結果集。

Result
------------
2024-12-31

C. 具有和不具有 month_to_add 參數的 EOMONTH

這些結果集中顯示的值反映且包含 12/01/202412/31/2024 之間的執行日期。

DECLARE @date DATETIME = '2024-12-31';

SELECT EOMONTH(@date) AS 'This Month';
SELECT EOMONTH(@date, 1) AS 'Next Month';
SELECT EOMONTH(@date, -1) AS 'Last Month';
GO

以下為結果集。

This Month
-----------------------
2024-12-31

Next Month
-----------------------
2025-01-31

Last Month
-----------------------
2024-11-30