SQL Server Queries - Get First Date of current month
SQL Server Queries - Get First Date of current month
Getting the First Date of the Current Month in SQL Server
In SQL Server, you can get the first date of the current month using the `DATEFROMPARTS` function and the `GETDATE()` function. Here's how to do it.
Syntax
The syntax to get the first date of the current month is as follows:
SELECT DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) AS FirstDateOfMonth; This query returns the first date of the current month.
Example
Let's say we want to get the first date of the current month:
SELECT DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) AS FirstDateOfMonth; This query will return the result:
| FirstDateOfMonth |
|---|
| 2023-03-01 |
The result shows that the first date of the current month (March 2023) is '2023-03-01'.
Alternative Syntax
You can also use the following alternative syntax to get the first date of the current month:
SELECT CAST(DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) AS DATE) AS FirstDateOfMonth; This syntax uses the `DATEADD` function to add the difference between the current month and the base date (0) to the base date, and then casts the result to a date.
Using a Variable
If you want to store the first date of the current month in a variable, you can use the following syntax:
DECLARE @FirstDateOfMonth DATE; SET @FirstDateOfMonth = DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1); SELECT @FirstDateOfMonth; This query declares a variable `@FirstDateOfMonth` and sets it to the first date of the current month using the `DATEFROMPARTS` function.