简体   繁体   中英

MySQL, CONCAT in SELECT statement

(SELECT CONCAT(@I, '_Delta') FROM table WHERE id_tb = @ID)

I'm using the above statement as part of an INSERT. The problem is the whole line is being translated to the value of @I (this is an index, values are ie 0, 1, 2, ...). So, instead of getting the output of the SELECT I'm getting 0, 1, 2, ...

The expected value of the CONCAT is like "0_Delta" , then "1_Delta" , etc. Replacing the CONCAT by one of this works.

Any comments will be appreciated. Thanks!

[code]

DROP TABLE IF EXISTS xxx_tb; CREATE TABLE xxx_tb ( i_Validity INT, Delta INT );

DROP TRIGGER IF EXISTS AFTER_INSERT_ON_tb_in; DELIMITER $$ CREATE TRIGGER AFTER_INSERT_ON_tb_in AFTER INSERT ON tb_in FOR EACH ROW BEGIN

SET @ID = NEW.id_tb;
SET @TYPE = (SELECT Type FROM header WHERE id_tb = @ID);


IF @TYPE = 'abcd' THEN

    SET @SAMPLES = (SELECT SampleNumber FROM table WHERE id_tb = @ID);

    IF(@SAMPLES > 1) THEN
        SET @I = 0;
        WHILE(@I < @SAMPLES) DO

            INSERT INTO xxx_tb
            (
                i_Validity, 
                Delta
            ) 
            VALUES 
            ( 
                (SELECT 0_Validity FROM table WHERE id_tb = @ID), 
                (SELECT CONCAT(@I, '_Delta') FROM table WHERE id_tb = @ID)
            );
            SET @I = @I + 1;

        END WHILE;

    END IF;

END IF;


END$$

DELIMITER ; [code]

delta is declared as an integer. You are getting a silent conversion from the string value. Because @i is at the beginning, that is the value you are getting.

You can try declaring it as varchar(255) if you want a string value.

Your insert can be written more easily as an insert . . . select insert . . . select insert . . . select :

    INSERT INTO xxx_tb(i_Validity, Delta) 
        SELECT `0_Validity`, CONCAT(@I, '_Delta')
        FROM table WHERE id_tb = @ID);

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