sql 按月查詢數據 不允許跨年

大概日期框這個樣子 查詢時 不可跨年 只能按月查在這裏插入圖片描述

sql代碼如下:

DECLARE @startTime datetime=null     --搜索的開始時間
DECLARE @endTime datetime=null      --搜索的結束時間
--以o.FinishTime爲基準
--@where爲查詢拼接
select @endtime=dateadd(day,1,@endtime)
--時間不爲空且查詢結束時間大於查詢開始時間且不允許跨年查詢
if @startTime is not null and @endtime is not null and  @endtime>@startTime and (DATEPART(yy,@endtime)-DATEPART(yy,@startTime)=0)
select @where =@where +' and o.FinishTime >='''+cast(@startTime as varchar(30)) +''' and o.FinishTime< '''+cast(@endtime as varchar(30))+''''
else if  @startTime is not null
select @where=@where+' and o.FinishTime>= '''+cast(@startTime as varchar(30))+''' and o.FinishTime< '''+cast(dateadd(year, datediff(year, 0, dateadd(year, 1, @startTime)), -1) as varchar(30))+''''
else if  @endtime is not null
select @where=@where+' and o.FinishTime< '''+cast(@endtime as varchar(30))+''' and o.FinishTime>= '''+cast(dateadd(year, datediff(year, 0, @endtime), 0) as varchar(30))+''''
 --查詢時間爲空時默認查詢本月第一天---最後一天  
else if @startTime is null and @endtime is NULL 
select @where =@where +' and o.FinishTime >='''+cast(dateadd(month, datediff(month, 0, getdate()), 0) as varchar(30)) +''' and o.FinishTime< '''+cast(dateadd(month, datediff(month, 0, dateadd(month, 1, getdate())), -1) as varchar(30))+''''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章