/**
 * This system procedure is used to return the 
 * definition text of the stored procedure from the 
 * database specified.
 */
create PROCEDURE psp_help_sp
(
    in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
    in :procedure_name  VARCHAR(254) -- Name of the stored procedure
)

RETURNS
(
    DATABASE_QUALIFIER  VARCHAR(20), -- Name of the database
    SP_TEXT             LONGVARCHAR -- Definition text of the stored procedure.
);

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);

    -- This variable stores the metadata version
    DECLARE :version           INTEGER;
    
    -- If the database qualifier is null, then use the current database
	if (:database_qual is null) then
		set :database_qual = DATABASE();
	end if;
	
    -- Check if the database qualifier specified is a 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 procedure name is null
	if (:procedure_name is null) then
		SIGNAL 'S1000', 'Procedure name cannot be null';
	end if;

    -- Check if the procedure name is a blank string
	if (rtrim(:procedure_name) = '') then
		SIGNAL 'S1000', 'Procedure name cannot be blank string';
	end if;		
	
    set :table_name = '"' + :database_qual + '".X$Proc' 
    	
    -- call procedure to find the metadata version and store it in a variable
    CALL psp_database_version(:database_qual, :version);

    if (:version = 1) then  
        -- Metadata version is V1
    
    set :query = 'SELECT ''' + :database_qual + ''', Xp$Misc FROM ' + 
                 :table_name + ' WHERE Xp$Name LIKE ''' + :procedure_name +
                 ''' and Xp$Flags <> 1 ORDER BY Xp$Id ';
    else 
        if (:version = 2) then  
   	    -- Metadata version is V2
	    
	    set :query = 'SELECT ''' + :database_qual + ''', Xp$Misc FROM ' + 
                 :table_name + ' WHERE Xp$Name LIKE ''' + :procedure_name +
                 ''' and Xp$Flags <> 1 ORDER BY Xp$Sequence ';

		end if;                     
    end if;

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

