Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 333
  • Last Modified:

Conditional Clauses in Where or And Section of a SQL statement in an Oracle Stored Procedure

I am converting from MS SQL Server to Oracle.  I've been tackling the problems one by one (with the help of Experts-exchange).  However this latest one is stumping me.

For example:

create or replace spGetTeams(teamID in number, teamName varchar2, crGetTeamInfo out sys_cursor)
as
Begin
open crGetTeamInfo for
Select team_name, team_id, team_record
From teams
where isActive = 1
And (team_id = teamID or teamID is null or teamID like '-1)
And (team_name = teamName or teamName is null or teamName like '%'||-1||'%')
null;
end spGetTeams;

The person that made the Stored procedure in MS SQL Server explained to me that that the -1 will return all records. So basically it will try to match to the parameter passed, or null records, or all records.  How would I go about doing this in PL/SQL?
0
vbemt
Asked:
vbemt
  • 3
1 Solution
 
MikeOM_DBACommented:
try this:

CREATE OR REPLACE PROCEDURE spgetteams (
   teamid          IN       NUMBER,
   teamname                 VARCHAR2,
   crgetteaminfo   OUT      sys_cursor
)
AS
BEGIN
   OPEN crgetteaminfo FOR
      SELECT team_name, team_id, team_record
        FROM teams
       WHERE isactive = 1
         AND (team_id = teamid OR teamid IS NULL OR teamid LIKE '%')
         AND (team_name = teamname OR teamname IS NULL OR teamname LIKE '%');
END;

Open in new window

0
 
MikeOM_DBACommented:

Small correction:
CREATE OR REPLACE PROCEDURE spgetteams (
   teamid          IN       NUMBER,
   teamname                 VARCHAR2,
   crgetteaminfo   OUT      sys_cursor
)
AS
BEGIN
   OPEN crgetteaminfo FOR
      SELECT team_name, team_id, team_record
        FROM teams
       WHERE isactive = 1
         AND (team_id = teamid OR (teamid IS NULL AND teamid LIKE '%'))
         AND (team_name = teamname OR (teamname IS NULL AND teamname LIKE '%'));
END;

Open in new window

0
 
vbemtAuthor Commented:
I think that's what I need, just have a miner question about the 2 examples you gave.  I'm trying to understand the difference between the 2.  I know one uses "AND" and the other uses "OR" but I don't see how it works.
0
 
MikeOM_DBACommented:

Difference is the first one had a typo: missing parenthesis.

Therefore you have this:

1) if parameter exists -> query ( column = parameter ...)
2) else (OR), if parameter does not exist ->  query (parameter IS NULL AND column like '%')


0

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now