Obtain the first day of the specified date month. You can use the DATEADD function to subtract the number of days that have elapsed since the month of the specified date.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
Return cast (DATEADD (day, 1-DAY (@ Date), @ Date) as datetime)
END
Alternatively, use DATEDIFF to calculate the number of months between the specified date and the start of the date, and then add DATEADD to the number of months, starting from scratch.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
Return dateadd (MONTH, DATEDIFF (MONTH, 0, @ Date), 0)
END
Alternatively, extract the year or month from the specified date and combine it with 01 to get the first day of the specified date.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ y NVARCHAR (4) = CAST (YEAR (@ Date) as nvarchar (4 ))
DECLARE @ m NVARCHAR (2) = CAST (MONTH (@ Date) as nvarchar (2 ))
Return cast (@ y + N'-'+ @ m + N'-01') as datetime)
END
Alternatively, refer to this article: The http://www.jb51.net/article/23285.htm uses the CONVERT function to specify the date format for conversion, which also gets the first day of the month of the specified date.
Copy codeThe Code is as follows:
Create function [dbo]. [udf_FirstDayOfMonth]
(
@ Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ ym NVARCHAR (10) = CONVERT (varchar (8), GETDATE (), 23)
Return cast (@ ym + n'01') as datetime)
END