/**
 * This system procedure is used to return the 
 * definition text of the user defined function from
 * the database specified.
 */
CREATE PROCEDURE psp_help_udf
(
    in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
    in :udf_name        VARCHAR(254) -- Name of the user defined function
)

RETURNS
(
    DATABASE_QUALIFIER  VARCHAR(20), -- Name of the database
    UDF_TEXT LONGVARCHAR -- Definiton text of the user defined function.
);

BEGIN

	-- This variable stores the dynamic query
	DECLARE :query      LONGVARCHAR;
	-- This variable stores the table name concatenated with 
	-- the database qualifier in the form dbname.tablename
    DECLARE :table_name VARCHAR(30);

    -- If the database qualifier specified is null, then use current database
	if (:database_qual is null) then
		set :database_qual = DATABASE();
	end if;
	
    -- Check if the database qualifier is blank string
	if (rtrim(:database_qual) = '') then
		SIGNAL 'S1000', 'Please enter a valid database name. Database name cannot be a blank string'; 
	end if;
	
    -- Check if the udf name is null
	if (:udf_name is null) then
		SIGNAL 'S1000', 'User-defined function name cannot be null';
	end if;

    -- Check if the udf name is a blank string
	if (rtrim(:udf_name) = '') then
		SIGNAL 'S1000', 'User-defined function name cannot be blank string';
	end if;		
	
    set :table_name = '"' + :database_qual + '".X$Proc' 

    set :query = 'SELECT ''' + :database_qual + ''', Xp$Misc FROM ' + 
                 :table_name + ' WHERE Xp$Name LIKE ''' + :udf_name +
                 ''' and Xp$Flags = 1 ORDER BY Xp$Id ';

    exec (:query);	
END;
 -- End of the stored procedure.
