大概日期框這個樣子 查詢時 不可跨年 只能按月查
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))+''''