DROP FUNCTION FN_BuildSQLQuery;

CREATE FUNCTION FN_BuildSQLQuery(
	a_all_cols varchar(1000),
	a_table_name varchar(50),
	a_filter_column varchar(50),
	filter_by_value varchar(50),
	a_addtional_where_clause varchar(500)
) 
RETURNS TEXT
DETERMINISTIC
BEGIN

DECLARE v_return_sql TEXT;
DECLARE v_table_columns TEXT;


SET v_return_sql = CONCAT('Select * from ( SELECT DISTINCT ', a_all_cols, ',', 'REPLACE( REPLACE( SUBSTRING_INDEX(SUBSTRING_INDEX( ');
SET v_return_sql = CONCAT(v_return_sql, a_filter_column, ', ",", n.digit+1), ",", -1), "]", "") , "[", "") val FROM ', a_table_name, ' INNER JOIN ');
SET v_return_sql = CONCAT(v_return_sql, ' (SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL  SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION  ALL SELECT 9) n ON LENGTH(REPLACE(', a_filter_column);
SET v_return_sql = CONCAT(v_return_sql, ', ",", "")) <= LENGTH(billing_mod_id)-n.digit ) demo_tab where val = ', filter_by_value);
SET v_return_sql = CONCAT(v_return_sql, ' AND ', a_addtional_where_clause);

RETURN (v_return_sql);

END
;