Friday, April 29, 2011

PL/SQL: Procedure not working correctly in a package

I'm working on a package with some procedures in them and I'm running into a bit of trouble. When I try to test the procedure to convert gallons to liters or the other procedures, it just prints out what was declared in the unnamed block instead of converting the numbers. Any ideas?

CREATE OR REPLACE PACKAGE eng_metric 
IS 
  PROCEDURE convert(degree_fahrenheit  IN OUT NUMBER,degree_celsius  IN OUT NUMBER,measure  IN VARCHAR2); 

  PROCEDURE convert(liters  IN OUT NUMBER,gallons  IN OUT NUMBER); 
END eng_metric; 
/ 

CREATE OR REPLACE PACKAGE BODY eng_metric 
AS 
  PROCEDURE Convert 
       (degree_fahrenheit  IN OUT NUMBER, 
        degree_celsius     IN OUT NUMBER, 
        measure            IN VARCHAR2) 
  IS 
    df         NUMBER; 
    dc         NUMBER; 
    convertf   NUMBER; 
    measurecf  VARCHAR2(4); 
  BEGIN 
    measurecf := measure; 

    df := degree_fahrenheit; 

    dc := degree_celsius; 

    IF measure = 'TEMP' THEN 
      IF dc = NULL THEN 
        convertf := ((df - 32) * .56); 

        degree_fahrenheit := convertf; 

        dbms_output.Put_line('The temperature in fahrenheit is ' 
                             ||To_char(degree_fahrenheit)); 
      ELSIF df = NULL THEN 
        convertf := (dc + 17.98) * 1.8; 

        degree_celsius := convertf; 
      END IF; 
    ELSE 
      dbms_output.Put_line('Invalid measure'); 
    END IF; 
  END convert; 

  PROCEDURE Convert 
       (liters   IN OUT NUMBER, 
        gallons  IN OUT NUMBER) 
  IS 
    lit        NUMBER; 
    gal        NUMBER; 
    convertlg  NUMBER; 
  BEGIN 
    lit := liters; 

    gal := gallons; 

    IF gal = NULL THEN 
      convertlg := (lit / 3.785); 

      liters := convertlg; 
    ELSIF lit = NULL THEN 
      convertlg := (gal * 3.785); 

      gallons := convertlg; 
    END IF; 
  END convert; 
END eng_metric; 
/ 

DECLARE 
  liters   NUMBER := 25; 
   gallons  NUMBER := 41; 
   nully    NUMBER := NULL; 
BEGIN 
  eng_metric.Convert(nully,gallons); 

  dbms_output.Put_line(To_char(gallons)); 
END; 
/ 

 
From stackoverflow
  • Instead of

    IF gal = NULL THEN
    

    you need

    IF gal IS NULL
    
    ninesided : there are a number of null checks that suffer from this problem
  • What you have to remember is that NULL means "no value". It NEVER equals or fails to equal anything, including NULL. So you need to use IS NULL or IS NOT NULL, or use the NVL function to change the null to something that has a value.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.