Mysql

將 null 傳遞給輸入參數時,儲存過程不顯示數據

  • August 20, 2020

我最近開始學習 MySQL 中的儲存過程,並創建了一個這樣的過程:

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_getAllDetails`(IN _student_no INT, 
IN _class_id INT, IN _subject_name VARCHAR(50) )
BEGIN
IF _student_no IS NOT NULL AND _class_id IS NULL  AND _subject_name IS NULL THEN
       SELECT DISTINCT S.Student_No, S.Student_Name, C.Class_id, S.Class,
       C.Class_desc, M.Eng_marks, M.Maths_marks, M.Science_marks FROM Student S 
       INNER JOIN Marks M ON S.Student_No = M.Student_No
       INNER JOIN Class C ON M.Class_id = C.Class_id
       WHERE S.Student_No  = _student_no;
      
       ELSE IF _class_id IS NOT NULL AND _student_no IS NULL AND _subject_name IS NULL THEN
       SELECT DISTINCT S.Student_Name, C.Class_id, S.Class, C.Class_desc,
       M.Eng_marks, M.Maths_marks, M.Science_marks FROM Student S 
       INNER JOIN Marks M ON S.Student_No = M.Student_No
       INNER JOIN Class C ON M.Class_id = C.Class_id
       WHERE  C.Class_id = _class_id;
       
       ELSE IF _subject_name IS NOT NULL AND _class_id IS NULL AND _student_no IS NULL THEN
       SELECT DISTINCT S.Student_Name, S2.Student_No, S2.Class_id, S1.Subject_Name, 
       S1.Subject_id, S3.Eng_marks, S3.Maths_marks, S3.Science_marks
       FROM Subject1 S1 
       INNER JOIN Subject2 S2 ON S1.Subject_id = S2.Subject_id 
       INNER JOIN Subject3 S3  ON S3.Student_No = S2.Student_No
       INNER JOIN Student S ON S.Student_Name = S2.Student_Name
       WHERE S1.Subject_Name  = _subject_name;
   END IF;
   END IF;
   END IF;
END

只有當我在工作台中呼叫這樣的過程時,它才會顯示所需的輸出:

call school.sp_getAllDetails(401, NULL, NULL);

但是,如果我從左側菜單中的快捷方式在對話框中輸入輸入參數,則與以下內容相同:

call school.sp_getAllDetails(401, NULL, 'NULL');

這不顯示任何數據,因為它將 NULL 作為字元串。我能知道我哪裡出錯了嗎?這將是一個很大的幫助。非常感謝

編輯: 將問題留在這裡,因為任何正在尋找相同問題的人都可以在這裡得到一些幫助。此外,如果有人有不同的答案,可以添加到此。

好吧,我自己解決了這個問題。_subject_name IS NULL我在第一個和第二個 IF 條件下都刪除了,它按預期工作。

引用自:https://dba.stackexchange.com/questions/273859