7

日付から日付までの小さな日時を使用して日付をフィルタリングする手順を書いています。開始日または終了日が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  

この行はどこが間違っているのか教えてください

4

2 に答える 2

14

それ以外の

WHEN @FromDate!=NULL AND @ToDate!=NULL

使用する

WHEN @FromDate IS NOT NULL AND @ToDate IS NOT NULL

IS [NOT] NULL

何かあればT-SQLNULLでは未定義なので比較できません。両方 (または両方) の値のいずれかが である場合、両方=!=生成されます。falseNULL

于 2013-10-31T08:08:55.183 に答える
2

クエリをフォーマットしてください。読書にははるかに優れています。

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  
于 2013-10-31T08:09:20.870 に答える