Calling a stored procedures within the same schema from a SP

谁都会走 提交于 2019-12-11 00:29:04

问题


How can I call a stored procedure in the same schema without specifying the full schema name when coding another stored procedure. These are SQL PL procedures within DB2.

First SP:

CREATE PROCEDURE MYSCHEMA.SP_TEST
  LANGUAGE SQL
  BEGIN
  END

Creating a SP calling this SP directly without a schema name causes a compilation error:

CREATE PROCEDURE MYSCHEMA.SP_TEST2
  LANGUAGE SQL
  BEGIN
    CALL SP_TEST();
  END

It will throw:

No authorized routine named "SP_TEST" of type "PROCEDURE" having compatible arguments was found.. SQLCODE=-440, SQLSTATE=42884, DRIVER=3.53.71

Directly giving the full schema name works:

CREATE PROCEDURE MYSCHEMA.SP_TEST2
  LANGUAGE SQL
  BEGIN
    CALL MYSCHEMA.SP_TEST();
  END

However if I ever move to a different schema I will have to replace that references all over the place. Is there a suitable workaround or nicer solution to the problem?


回答1:


The CURRENT PATH special register is used to resolve calls to unqualified stored procedures and functions. CURRENT SCHEMA is used to resolve unqualified object names.

By default, CURRENT PATH has IBM functions plus your AUTHID:

$ db2 "values substr(current path,1,60)"

1
------------------------------------------------------------
"SYSIBM","SYSFUN","SYSPROC","SYSIBMADM","IBJORHOV"

  1 record(s) selected.

You can modify this with the SET CURRENT PATH statement.

When you create a stored procedure, DB2 takes note of the value of CURRENT PATH at compilation time and uses them to resolve unqualified stored procedure and function calls within the stored procedure. The same logic applies for CURRENT SCHEMA and unqualified table names.

So the proper way to allow unqualified procedure and function calls within a stored procedure is to set the CURRENT PATH register and then creating the procedure.




回答2:


Ommitting SCHEMA name is discouraged. Keep your schema names in your calls. If you move to a different schema, you have to do this by extracting/altering the SQL script anyway.




回答3:


The SET SCHEMA command allows you to change the current schema:

SET CURRENT SCHEMA FOO;
CALL MY_PROC_THAT_RESIDES_IN_FOO();

It is not so easy to use set the schema to a dynamic value, though. You would have to either:

  1. Do something with host variables (if you are within a calling application) or
  2. Build and execute a dynamic SQL statement string.

At that point it is probably becoming more trouble than it's worth.

More information can be found at the documentation for the SET SCHEMA command.



来源:https://stackoverflow.com/questions/12617787/calling-a-stored-procedures-within-the-same-schema-from-a-sp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!