DECLARE @startMonth int
DECLARE @endMonth int
DECLARE @startYear int
DECLARE @endYear int
SET @startMonth = 1
SET @endMonth =5
SET @startYear =2014
SET @endYear =2015
SELECT * FROM Table
WHERE (YEAR(Date)>=@startYear AND MONTH(Date) >= @startMonth)
AND (YEAR(Date)<=@endYear AND MONTH(Date) <= @endMonth)
这显然是2014-01-01至2014-05-31之间任何日期的结果
和2014-01-01至2015-05-31
但我希望从2014-01-01到2015-05-31获得任何日期。
我该如何更改查询?我应该写下面的内容?
SELECT * FROM Table
WHERE Date>=DATEFROMPARTS ( @startYear, @startMonth, 1 )
AND Date <= DATEFROMPARTS ( @endYear, @endMonth, 31 ))
然后我最终得到的问题是,如果@endMonth不包含31天。然后我必须创建另一个检查以确保结束日期的正确数量。
我相信必须有更好的方法来写这个。我很感激你的帮助。
答案 0 :(得分:1)
SELECT *
FROM your_table
WHERE Date >= DATEFROMPARTS(@startYear, @startMonth, 1)
AND Date < DATEFROMPARTS(@endYear, @endMonth + 1, 1)
答案 1 :(得分:0)
SELECT *
FROM
<table_name>
WHERE
date BETWEEN DATEFROMPARTS(@startYear,@startMonth,1) AND EOMONTH(DATEFROMPARTS(@endYear,@endMonth,1));