I have the following structure in my DB:
id,col_a,col_b,col_c,etc...
Now, all the other columns except for id are of type boolean. Lets say for example that
col_a=1,
col_b=0,
col_c=1
I am looking for a way to return the names of the columns where the column is true (=1), so in this example the return should look something like col_a,col_c
There will be a dynamic number of columns, seeing as the table is altered often to add new columns and delete old ones.
The function I have thus far looks like this - it is the function that is supposed to return that string of column names...
DROP FUNCTION fn_access;
DELIMITER //;
CREATE FUNCTION fn_access (myid INT) RETURNS varchar(800)
DETERMINISTIC
BEGIN
DECLARE ret_val VARCHAR(800);
DECLARE col_name VARCHAR(255);
DECLARE i INT;
DECLARE num_rows INT;
DECLARE col_names CURSOR FOR
SELECT column_name
FROM information_schema.columns
WHERE `table_name` = 'access' AND `table_schema` = 'some_db' AND `column_name` <> 'id'
ORDER BY ordinal_position;
SELECT FOUND_ROWS() into num_rows;
SET i = 1;
the_loop: LOOP
IF i > num_rows THEN
CLOSE col_names;
LEAVE the_loop;
END IF;
FETCH col_names
INTO col_name;
SET ret_val = CONCAT(',' col_name);
SET i = i + 1;
END LOOP the_loop;
SELECT * FROM access WHERE id = @myid;
RETURN ret_val;
END
//
Is there any way to do this using straight SQL? I am using MySQL.