DROP FUNCTION IF EXISTS fnGetJoinString;

delimiter $$

CREATE FUNCTION fnGetJoinString (	oldTableType INT, 
									MasterTableName varchar(28),
									strPrimaryColumnName varchar(28), 
									strSecondaryTableName varchar(28), 
									strSecondaryColumnName varchar(28), 
									strThirdTableName varchar(28), 	
									strThirdColumnName varchar(28), 
									strFourthColumnName varchar(28)
								)
	RETURNS varchar(5000)
	BEGIN 
		DECLARE strJoinString varchar(5000);

					 CASE oldTableType
						WHEN 1 THEN 
							SET strJoinString := '';
						WHEN 2 THEN
							SET strJoinString := CONCAT(' INNER JOIN ', strSecondaryTableName, ' ON ', MasterTableName,
														'.', strPrimaryColumnName, ' = ', strSecondaryTableName, '.', strSecondaryColumnName);
						WHEN 3 THEN
							SET strJoinString := CONCAT(' INNER JOIN ', strSecondaryTableName, ' ON ', MasterTableName,
														'.', strPrimaryColumnName, ' = ', strSecondaryTableName, '.', strSecondaryColumnName,
														' INNER JOIN ' , strThirdTableName, ' ON ', strThirdTableName, '.', strThirdColumnName,
														' = ', strSecondaryTableName, '.', strFourthColumnName );
						WHEN 4 THEN
							SET strJoinString := CONCAT(' INNER JOIN ', strSecondaryTableName, ' ON ', MasterTableName,
														'.', strPrimaryColumnName, ' = ', strSecondaryTableName, '.', strSecondaryColumnName);
					 END CASE;
		RETURN strJoinString;
	END $$
 
DELIMITER ;