简体   繁体   中英

set variable to column name mysql

I am trying to loop through a table adl_weight that has a column with the exact names of a column from another table adl_activities . I am trying to grab the column name from the table and use that to grab the value of the column on the second table.

Is it possible to do this with mysql? I have tried to use prepared statements but so far these aren't working.

set i = 1;
select count(*) from adl_weight into n;

WHILE(i<n) DO
    set tmp_condition =(select user_condition from adl_weight where row_number = i);
    set tmp_score = (select tmp_condition from adl_activities where userid = id);

    if(tmp_score > 0) then
        #do items here
    end if;
END WHILE;

If I understand you correctly, you need to grab a column whose name is defined in a variable.

The problem is that mysql doesn't let you insert variables as anything other than values, but you can create a new string which contains a command with the variable's value as the column name and execute that. Here's an example:

SET @sql = CONCAT("SELECT `", @columnName, "` FROM tableA");
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Edit: If you want to select into a variable instead, you can use this:

SET @sql = CONCAT("SELECT ", @columnName, "` FROM tableA INTO @result");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM