/**
 * This system procedure is used to return the list
 * of groups and the corresponding information from the 
 * database specified.
 */
CREATE PROCEDURE psp_groups
(
    in :database_qual   VARCHAR(20) = DATABASE(), -- Name of the database
    in :group_name      VARCHAR(254) = NULL -- Name of the group
)
RETURNS
(
    DATABASE_QUALIFIER  VARCHAR(20), -- Name of the database
    GROUP_ID            USMALLINT, -- Group ID
    GROUP_NAME          VARCHAR(254)   -- Name of the group
);
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 database qualifier is null, use the current database
	if (:database_qual is null) then
		set :database_qual = DATABASE();
	end if;

    -- Check if the database qualifier 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 group name is a blank string.
    if (rtrim(:group_name) = '') then
        SIGNAL 'S1000', 'Please enter a valid group name.Group name cannot be a blank string';
    end if;

	/* If group name is null or not supplied, 
	   match all the groups */
		
	SET :group_name = IFNULL(:group_name,'%');
	
	-- Enumerate the group ids and the group names

    SET :table_name = '"' + :database_qual + '".X$User';

    SET :query = ' SELECT ''' + :database_qual + 
                 ''' ,A.Xu$Id, A.Xu$Name FROM ' + :table_name +
                 ' A WHERE A.Xu$Name LIKE ''' + :group_name + 
                 ''' AND  A.Xu$Flags & 64 = 64 ';     -- Check whether the name is a group name. 
    exec (:query);
	
END; -- End of stored procedure.

