2

I want to create a table dynamical but my built string to create the table is NULL - why?
The goal is to get column values from an existing table and create a new table with columns named with these values.

DELIMITER $$
DROP PROCEDURE IF EXISTS fanart_test.get_incomplete_artwork $$
CREATE PROCEDURE fanart_test.get_incomplete_artwork()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE type_id INT;
DECLARE type_name INT;
DECLARE build_string VARCHAR(20000);

DECLARE cursor1 CURSOR FOR 
    SELECT type_id,type_name FROM fanart_types WHERE type_section = 3;


DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

OPEN cursor1;

get_results: LOOP
    FETCH cursor1 INTO type_id, type_name;
    IF finished = 1 
    THEN LEAVE get_results;
    END IF;

    IF build_string = ""
    THEN SET build_string = CONCAT('CREATE TABLE `tmp_incomplete_artwork`(`', type_name, '` TEXT');
    ELSE SET build_string = CONCAT(build_string,',', type_name);
    END IF;

    SET build_string = CONCAT(build_string,')');

END LOOP get_results;
CLOSE cursor1;

SET @s = build_string;
PREPARE build FROM @s;
EXECUTE build;
DEALLOCATE PREPARE build;

END $$

1 Answer 1

1
DECLARE build_string VARCHAR(20000);

The build_string is not set to anything initially, so it'll probably be NULL.

IF build_string = ""

This will never return true, since NULL = "" is not true.

ELSE SET build_string = CONCAT(build_string,',', type_name);

Concatenating any string with NULL returns NULL.


Re your comment:

You have named your variables type_id and type_name which are the same as your column names in your table. This creates an ambiguity, and it turns out that MySQL prefers to interpret the identifiers as the local variables, instead of column names.

So this:

SELECT type_id,type_name FROM fanart_types WHERE type_section = 3;

Will return the current value of type_id and type_name, which is uninitialized, i.e. NULL. Therefore a pair of NULLs are returned for all rows of the table.

Just rename the variables to be distinct from your table's column names, or else qualify the columns so they are clearly columns instead of variables:

SELECT f.type_id, f.type_name FROM fanart_types f WHERE f.type_section = 3;

Also you probably want to declare type_name as TEXT instead of INT.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.