Oracle sql return true if exists question

后端 未结 5 1310
清酒与你
清酒与你 2021-01-03 21:12

How do I check if a particular element exists in a table - how can I return true or false?

I have a table that has

  • user_id
  • user_password
5条回答
  •  无人及你
    2021-01-03 21:38

    In PL/SQL you can do this:

    function user_exists (p_user_id users.user_id%type) return boolean
    is
      l_count integer;
    begin
      select count(*)
      into   l_count
      from   users
      where  user_id = p_user_id;
    
      return (l_count > 0);
    end;
    

    This would then be used in calling PL/SQL like this:

    if user_exists('john') then
      dbms_output.put_Line('John exists');
    end if;
    

    NOTE: I used count(*) in the query in the knowledge that this will only return 1 or 0 in the case of a primary key search. If there could be more than one row then I would add "and rownum = 1" to the query to prevent unnecessarily counting many records just to find out if any exists:

    function user_has_messages (p_user_id users.user_id%type) return boolean
    is
      l_count integer;
    begin
      select count(*)
      into   l_count
      from   messages
      where  user_id = p_user_id
      AND ROWNUM = 1;
    
      return (l_count > 0);
    end;
    

提交回复
热议问题