在SQL Server 2008中,我将startdate和enddate传递给我的过程。我需要检查范围中的每个日期,看看它是否存在于我的validworkday表中。我不知道从哪里开始,但这是设置开始/结束日的方式
Declare @startdate date, @enddate date
Set @startdate = '01/01/2015'
Set @enddate = '04/16/2015'
现在我如何迭代此范围中的每个日期以查看validworkday = true?我需要运行的检查是这样的(检查每个日期)
Select isvalidworkday
from validworkdays
where date = '01/01/2015'
Select isvalidworkday
from validworkdays
where date = '01/02/2015'
答案 0 :(得分:0)
这是我在@Incidently几年前发现的语法(我不记得那个原始帖子在哪里,但希望这足以给予奖励),我今天仍在使用。我所做的只是略微调整他的语法,将数据插入到临时表中,并添加一个游标来迭代每个日期。
DECLARE @DateFrom smalldatetime, @DateTo smalldatetime, @firstdate date;
SET @DateFrom='20000101';
SET @DateTo='20081231';
-------------------------------
WITH T(date)
AS
(
SELECT @DateFrom
UNION ALL
SELECT DateAdd(day,1,T.date)
FROM T
WHERE T.date < @DateTo
)
SELECT date
INTO #AllDates
FROM T OPTION (MAXRECURSION 32767);
Declare c1 Cursor For
Select date
FROM #AllDates
Open c1
Fetch Next From c1 Into @firstdate
While @@FETCH_STATUS = 0
Begin
--Do whatever processing you need here
Fetch Next From c1 Into @firstdate
End
Close c1
Deallocate c1
答案 1 :(得分:0)
代码应该只存在于一个地方而不能被重写。创建函数(一次),如GetAllIntsBetween(),GetAllMonths(),GetAllDates()等。然后使用它们像:
SELECT *
FROM posts
WHERE `like` BETWEEN 5 AND 25 AND bp = '0'
ORDER BY id DESC
LIMIT 15 ;
GetAllDates()将是:
DECLARE @startdate date = '01/01/2015', @enddate date = '04/16/2015'
SELECT allDates.TheDate,
isnull(v.isvalidworkday, false) AS isvalidworkday
FROM dbo.GetAllDates(@startdate, @enddate) AS allDates
LEFT JOIN validworkdays AS v
ON allDates.TheDate = v.MyDate
(注意:可以将DATETIME更改为DATE)