如何在SQL SERVER中获取给定月份和年份的完整日期?

时间:2014-08-26 23:03:36

标签: sql-server-2012

我有以下脚本需要获取完整日期

DECLARE @BeginDate DateTime
DECLARE @EndDate DateTime
Declare @month int
Declare @year int 
set @month = 6
set @year = 2014

Select beginDate = CAST(@month AS VARCHAR(10)) + '/01/' + CAST(@year AS VARCHAR(10))
SELECT endDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @beginDate) + 1, 0))

此脚本将endDate返回为null。如何通过仅传递日期(而不是时间)来获得完整的endDate?

2 个答案:

答案 0 :(得分:1)

我想你忘了把@符号放在变量前面。如果您使用以下内容更改最后两行:

Select @beginDate = CAST(@month AS VARCHAR(10)) + '/01/' + CAST(@year AS VARCHAR(10))
SELECT @endDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @beginDate) + 1, 0))

它应该有用。通过将“select @enddate”放在最后,我得到了2014-06-30 00:00:00.000。

答案 1 :(得分:0)

我找到了。

DECLARE @BeginDate DateTime
DECLARE @EndDate DateTime
Declare @month int
Declare @year int 
set @month = 7
set @year = 2014

Select @beginDate = CAST(@month AS VARCHAR(10)) + '/01/' + CAST(@year AS VARCHAR(10))
SELECT endDate = DATEADD(d, -DAY(DATEADD(mm, 1, @beginDate)), DATEADD(m, 1, @BeginDate))

source