Search code examples
mysqlstored-proceduresconcatenationcreate-table

EDIT mysql tablename to combine with value of one column (concatenate)


I have a table called 'Details', the Details table has a few columns, one being 'TicketNumber'.

What I am hoping to do is name the table 'Details_TicketNumber' --- not the actual word but the value of the first/highest ticket number.

e.g if the TicketNumber is '12345'

the table name would be Details_12345

How would I be able to do this? I've been searching for a few hours and no luck today.. Thanks

This is what I have tried (and realized it wouldn't work)

attempt 1:

Rename table details 
to  (select concat("details",details.ticketnumber));

Attempt 2:

set @sql = CONCAT(details,
                  details.TicketNumber)
                 );

prepare s from @sql;

execute s;

Solution

  • As suggested by @JeffUK and the reference he pointed out. I believe this should work inside a stored procedure.

    DECLARE highest_ticket INT DEFAULT 0;
    
    SELECT MAX(ticket_number) INTO highest_ticket 
    FROM details;
    
    set @s = CONCAT('RENAME TABLE details to details_',highest_ticket); 
    prepare renameTable from @s;
    EXECUTE renameTable ;
    DEALLOCATE PREPARE renameTable ;