DROP FUNCTION IF EXISTS CheckInGroup;
DELIMITER //
CREATE FUNCTION CheckInGroup
(
  p_sid INT,
  p_gid INT
)
RETURNS INT
READS SQL DATA
BEGIN
SET @outputCode :=(
    SELECT
    (
        CASE 
            WHEN p_gid = 0 THEN 0
            WHEN p_gid = 1 THEN 42
        ELSE 100
        END
    )
);

IF @outputCode = 100 THEN

    SET @outputCode :=(
        SELECT
        (
            CASE 
                WHEN(
                    SELECT
                        COUNT(*)
                    FROM
                        groupes
                    WHERE
                        ID = p_gid
                ) = 1 THEN 42
            ELSE 2012
            END
        )
    );
    IF @outputCode = 42 THEN

        SET @outputCode :=(
            SELECT
            (
                CASE 
                    WHEN(
                        SELECT
                            COUNT(*)
                        FROM
                            appartenanceAUnGroupe
                        INNER JOIN groupes
                        ON groupes.ID = appartenanceAUnGroupe.groupID
                        WHERE
                            groupes.ID = p_gid AND appartenanceAUnGroupe.membreID = p_sid
                    ) >= 1 THEN 42
                    ELSE 0
                END
            )
        );
    END IF;
END IF;
RETURN @outputCode;

END//
DELIMITER ;

