/**
 * This system procedure is used to return the 
 * list of views from the database specified.
 */
CREATE PROCEDURE psp_views
(   
	in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
    in :view_name       VARCHAR(255) = NULL -- Name of the view
)

RETURNS
(
    VIEW_QUALIFIER  VARCHAR (20), -- Name of the database that contains the View
    VIEW_OWNER      VARCHAR (20),  -- owner of the View
    VIEW_NAME       VARCHAR(255), -- Name of the view
    REMARKS         VARCHAR(255),	-- Remarks
    TRUSTEE         INT          -- Trustee column for V2
);

BEGIN
    -- Variable to hold the dynamic query 
    DECLARE :stmt_psp_views LONGVARCHAR;

    -- Variable to store the Database version
    DECLARE :version INTEGER;

    -- 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 view name specified is a blank string
	if (rtrim(:view_name) = '') then
		SIGNAL 'S1000', 'View name cannot be a blank string'; 
	end if;
    
	/*	If view name is null or not supplied, 
	    match all the views */

	SET :database_qual = IFNULL(:database_qual,database());

	SET :view_name = IFNULL(:view_name,'%');

    -- Get the DB Version
	CALL psp_database_version(:database_qual, :version);

    IF (:version = 1) THEN
	set :stmt_psp_views  = 'SELECT ''' +
						   	:database_qual + 
							''', null, ' + 
							' Xv$Name, ' +
                                ' null, null '+
							' FROM "'+ :database_qual + '".X$View ' +
							' WHERE Xv$Name LIKE ''' + :view_name + ''';'
    ELSE
    --IF (:version = 2) THEN
	set :stmt_psp_views  = 'SELECT ''' +
						   	:database_qual + 
							''', null, ' + 
							' Xv$Name, ' +
                                ' null, Xv$Trustee '+
							' FROM "'+ :database_qual + '".X$View ' +
							' WHERE Xv$Name LIKE ''' + :view_name + ''';'
    END IF;                                
        

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

