1

I am writing a C++ program using OCI to call the stored procedure. In my PL/SQL stored procedure test, if not initializing an outbound variable, I might get "fetched column value is NULL" error because in case of foo != 0, bar is NULL. So in the first line, I initialize bar first. Is this the right way to handle outbound variable?

  FUNCTION function1(
    foo   IN  INTEGER,
    bar   OUT VARCHAR2
  ) RETURN INTEGER
  IS
    ret      INTEGER;
  BEGIN

    bar := ' '; -- do I need to initialize this variable?

    IF foo = 0 THEN
      ret := 0;
      bar := 'a';
    ELSE
      ret := 1;
    END IF;

    RETURN ret;

  END function1;
5
  • How can you get a fetched column value is Null error when there is no select (i.e. fetch) in your function? and bar := ' '; is not required, but you can do it as bar := NULL; Aug 16, 2012 at 16:21
  • The sql command executed in C++ looks like BEGIN\n:ret := function1(:foo, :bar); END; It does error out even there's no select statement. And I tested it again, doing bar := NULL; causes the same error as well!
    – Stan
    Aug 16, 2012 at 16:51
  • Have you tried initializing the variable as shown in the code posted above, and does that eliminate the error? Aug 16, 2012 at 17:13
  • I tried var := NULL and it's still causing error.
    – Stan
    Aug 17, 2012 at 9:20
  • Functions with OUT parameters are a bad programming style, IMO. I'd recommend coding this as a procedure with two OUT parameters. Aug 21, 2012 at 8:00

1 Answer 1

1

If you don't set BAR in your program then the variable will be initialized to the default value of its type (NULL in this case, and for any type except for a record type with a non-NULL default value). That's just basic logic.

So your choices are:

  1. Accept the default value for the type of your variable.
  2. Set BAR to the appropriate value in each branch of the IF statement.

Your posted code uses the first option. In the simple logic you present that is the approach I would take. If the internals were more complicated - an IF or a CASE with many branches - I would choose to have every branch explicitly set the value, because that would probably make the code's intent clearer.

2
  • bar is an OUT parameter, which means it will be NULL at the start of the function call. Not "whatever value it had before you called function1()". Aug 21, 2012 at 7:58
  • @JeffreyKemp - quite right. I happened to have been working with IN OUT parameters, and I had their behaviour on the brain.
    – APC
    Aug 21, 2012 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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