Question

I have tables like,

Table A

field1  | field2 | field3 | field4 | field5 

Table B

id    | field_names
--------------------
1       field2
2       field3

I have to delete field2 and field3 from Table A ( means field names in Table B ).

Is there any way to drop field names which present in Table B. I can't delete the fields manually.

Thanks in advance

Was it helpful?

Solution 2

Not sure why you need this. anyway MySQL has no such feature. but if you want really do that, execute following query and execute each rows.

SELECT CONCAT('ALTER TABLE TableA DROP ', field_names, ';') FROM TableB;

for examples with PHP, (all error check is omitted)

$query = "SELECT CONCAT('ALTER TABLE TableA DROP ', field_names, ';') AS stmt FROM TableB;";

$result = mysqli_query($query);

while ($row = mysqli_fetch_assoc($result))
{
    mysqli_query($rows['stmt']);
}

OTHER TIPS

This would help:

SELECT @s := CONCAT('ALTER TABLE tableA DROP COLUMN ', GROUP_CONCAT(field_names SEPARATOR ', DROP COLUMN '), ';') FROM tableB;
PREPARE stmt FROM @s;
EXECUTE @s;

First create a procedure:

DELIMITER //
CREATE PROCEDURE deleteTableAColumns()
BEGIN
    DECLARE columnToDelete VARCHAR(16);
    DECLARE done INT DEFAULT FALSE;
    DECLARE columnsToDeleteCur CURSOR FOR SELECT field_names FROM tableB;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN columnsToDeleteCur;
    read_loop: LOOP 
        FETCH columnsToDeleteCur INTO columnToDelete;
        IF done THEN
            LEAVE read_loop;
        END IF;
        SET @dropColumnQuery = CONCAT('ALTER TABLE tableA DROP ', columnToDelete, ';');
        PREPARE dropColumnQueryStatement FROM @dropColumnQuery;
        EXECUTE dropColumnQueryStatement;
        DEALLOCATE PREPARE dropColumnQueryStatement; 
    END LOOP;
    CLOSE columnsToDeleteCur;
END
//
DELIMITER ;

Then call the procedure whenever you want to execute it:

CALL deleteTableAColumns();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top