-4

I am trying to figure out an assignment. The text is:

Write a stored function which will return the course id that the course name contain a given parameter pattern string. You must use LIKE for the pattern match. Please refer to Courses table.

  • If a character such as Z is entered, and it is not in the courses name should display: No record found

  • If the input is blank: Please input a valid string

  • If the input is NULL: Please input a valid string

  • And if the input is J: CPS1231, CPS2231

Courses table

cid     | name
--------+------------------
CPS1231 | Java1
CPS2231 | Java2
CPS2232 | Data Structure

Here's what I have so far:

CREATE FUNCTION `Work` ()
RETURNS INTEGER
BEGIN

    declare msg varchar(20) default '';
    
    if ((name is null) or (name='')) then
        select "Please input a valid string" as message;
    else
    select group_concat(name) into msg from dreamhome.Courses where name like '%,_name%';
    
    
    elseif ((msg='') or (msg is null)) then
        select group_concat(" is not in the system") as message;
    else
        select distinct cid from dreamhome.Courses;

    end if;
end if;

I'm not sure where to go from here.

2
  • 1
    Which dbms are you using?
    – jarlh
    Nov 22, 2018 at 20:21
  • Doing it through SQL workbench not sure which one @jarlh Nov 22, 2018 at 22:52

1 Answer 1

0
CREATE FUNCTION get_id(NAME IN 
Courses.NAME%TYPE ,COURSE_ID_O[] OUT ARRAY )
RETURN COURSE_ID_O
BEGIN 
IF NAME LIKE '_J%' OR NAME LIKE '_Z%'
THEN
 SELECT  COURSE_ID INTO COURSE_ID_O FROM 
 COURSES WHERE COURSE_NAME=NAME ;
 ELIF NAME='' OR NAME=NULL
   THEN
      DBMS_OUTPUT.PUT_LINE('Please enter a valid string.');


 END IF
 EXCEPTION
 WHEN NO_DATA_FOUND THEN
 DBMS_OUTPUT.PUT_LINE('No record found If it is blank 
 or null: Please input a valid string');
 END EXCEPTION
 END

You might refer the correct syntax but for the above as general case it means the function get_id will take name and will return course_id_o array as there are multiple rows in it as O/p if the input course name is J then it will print else the default error message.

4
  • I get the basics but there suppose to be 3 statements don't all three of them need an if statement? Nov 22, 2018 at 22:54
  • Check what i have written why you require 3 seperate ifs one if else loop can do the needful because you want to transfer the control as if (input does nt match this go to elif and finally else in seperate it will forcefully check all the ifs seperately all the time but in if else it will check upto if its valid in the worst case it will go to else if the input is null or none.
    – Himanshu
    Nov 23, 2018 at 4:55
  • Ahh got it, thank you very much so it basically shortens it but does the same thing Nov 23, 2018 at 20:21
  • Exactly :).....
    – Himanshu
    Nov 23, 2018 at 20:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.