如何从SQL中的月份ID和年份获取特定月份的最后日期?
输入:
@MonthID INT = 2,
@Year INT = 2015
必需输出:28/02/2015
答案 0 :(得分:1)
在SQL Server 2012 +
中很容易要使用年份和月份构建日期,请使用 DATEFROMPARTS (Transact-SQL)
要查找月份的最后一天,请使用 EOMONTH (Transact-SQL)
function mymodule_theme() {
return array(
'mymodule_form_weights' => array('arguments' => array('form' => null)),
);
}
对于任何少于Declare @MonthID INT = 2,
@Year INT = 2015
SELECT Eomonth(Datefromparts(@Year, @MonthID, 1))
Sql server 2012
注意:如果变量属于SELECT Dateadd(dd, -1, Dateadd(mm, 1, Cast(Cast(@Year AS CHAR(4)) + '-'
+ Cast(@MonthID AS VARCHAR(2))+'-'+'1' AS DATE)))
类型,则可以将Varchar
删除为varchar
答案 1 :(得分:1)
您可以按以下方式找到该月的最后一天
Declare @MonthID varchar(10) = '02', @Year varchar(10) = '2015'
select dateadd(dd,-1,dateadd(MM,1,cast(@Year+'-'+@MonthID+'-1' as date)))
答案 2 :(得分:0)
这就是我做到的。
DECLARE @MonthID INT = 3,
@Year INT = 2015
DECLARE @InputDate DATE, @TempDate DATE, @OutputDate DATE
SET @InputDate = CAST(CAST(@Year AS VARCHAR) + '-' + CAST(@MonthID AS varchar) + '-01' AS DATE)
SET @TempDate = @InputDate
WHILE (DATEPART(m, @InputDate) = DATEPART(m, @TempDate))
BEGIN
SET @OutputDate = @TempDate
SET @TempDate = DATEADD(d,1,@TempDate)
END
SELECT @OutputDate