我正在编写程序,我希望使用从日期到日期的小日期时间来过滤日期。 从某个时候起,日期可以为null,而在比较时,To Date也可以为null 当日期或日期可以为空时,过滤日期。
我尝试过以下查询,但它给了我错误。
SELECT RQ.int_REPS_QUES_DIFF_LEVEL,SUM(1) AS NoOFDificultyQuestion FROM
REPS_TEST_QUES_ASSIGNED RQA
INNER JOIN REPS_QUESTION RQ ON RQA.int_REPS_TEST_QUES_ASSG_QUESID=RQ.PK_REPS_QUES_ID
WHERE int_REPS_TEST_ID IN(
SELECT FK_TEST_ID FROM STUDENT_EXAM SE WHERE FK_USER_ID=56 AND SE.FK_REPS_BATCH_ID=466
and CASE
WHEN @FromDate!=NULL AND @ToDate!=NULL
THEN dat_STUD_EXAM_FINALEND >= @FromDate AND dat_STUD_EXAM_FINALEND <= @ToDate
WHEN @FromDate!=NULL AND @ToDate=NULL
THEN dat_STUD_EXAM_FINALEND >= @FromDate
WHEN @FromDate=NULL AND @ToDate!=NULL
THEN dat_STUD_EXAM_FINALEND <= @ToDate
END
)
strong textGROUP BY RQ.int_REPS_QUES_DIFF_LEVEL
我在
收到错误THEN dat_STUD_EXAM_FINALEND >= @FromDate AND dat_STUD_EXAM_FINALEND <= @ToDate
这一行请告诉我哪里出错了
答案 0 :(得分:11)
而不是
WHEN @FromDate!=NULL AND @ToDate!=NULL
使用
WHEN @FromDate IS NOT NULL AND @ToDate IS NOT NULL
如果某些内容为NULL
,则在T-SQL中未定义,因此您无法与之进行比较。如果两个(或两个)值中的一个为=
,则!=
和false
都会产生NULL
。
答案 1 :(得分:1)
请格式化您的查询。阅读会好得多。
SELECT RQ.int_REPS_QUES_DIFF_LEVEL,
SUM(1) AS NoOFDificultyQuestion
FROM REPS_TEST_QUES_ASSIGNED RQA
INNER JOIN REPS_QUESTION RQ
ON RQA.int_REPS_TEST_QUES_ASSG_QUESID=RQ.PK_REPS_QUES_ID
WHERE int_REPS_TEST_ID IN
(
SELECT FK_TEST_ID
FROM STUDENT_EXAM SE
WHERE FK_USER_ID=56
AND SE.FK_REPS_BATCH_ID=466
AND (
--If both dates are not NULL then also check dat_STUD_EXAM_FINALEND to be between them
(@FromDate IS NOT NULL AND @ToDate IS NOT NULL AND dat_STUD_EXAM_FINALEND >= @FromDate AND dat_STUD_EXAM_FINALEND <= @ToDate )
OR
--If @FromDate is not NULL AND @ToDate IS NULL then also check dat_STUD_EXAM_FINALEND to be greater than @FromDate
(@FromDate IS NOT NULL AND @ToDate IS NULL AND dat_STUD_EXAM_FINALEND >= @FromDate )
OR
--If @FromDate is NULL AND @ToDate IS NOT NULL then also check dat_STUD_EXAM_FINALEND to be less than @ToDate
(@FromDate IS NULL AND @ToDate IS NOT NULL AND dat_STUD_EXAM_FINALEND <= @ToDate )
--Having AND in each set makes it impossible two sets to be true at the same time.
--So If both dates are not null the first set will be evaluated.
--If @ToDate is NULL, then the first and third sets won't be evaluated as they need @ToDate to be not NULL
--If @FromDate is NULL, then the first and second sets won't be evaluated as they need @FromDate to be not NULL
)
) strongtext GROUP BY RQ.int_REPS_QUES_DIFF_LEVEL