获取指定日期月份的第一天,你可以使用DATEADD函数,减去指定日期的月份过去了的天数,即可。
udf_FirstDayOfMonth
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(DATEADD(day,1 - DAY(@Date), @Date) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(DATEADD(day,1 - DAY(@Date), @Date) AS DATETIME)
END
或者,用DATEDIFF计算指定日期与日期开始之时,相隔几个月,然后再DATEADD加上这个相隔月份数,从零开始。
udf_FirstDayOfMonth
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
END
或者,从指定的日期取出年或月,然后与01组合为日期,即得到指定日期当月天第一天。
udf_FirstDayOfMonth
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
(
@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
或者,参考这篇:http://www.cnblogs.com/insus/articles/1554836.html 使用CONVERT函数,指定日期格式来转换,这样也可以获取指定日期所在月份的第一天。
udf_FirstDayOfMonth
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
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ym NVARCHAR(10) = CONVERT(varchar(8),GETDATE(),23)
RETURN CAST((@ym + N'01') AS DATETIME)
END