채택완료

DB에서 특정 접두어 필드 일괄 삭제법 ?

예를 들어, sir_  라는 접두어 필드를 모든 테이블에서 제거하려면 ?

에전 왕계란 님이 적어주신 코드는 특정 접두어 테이블을 컨트롤 하는 건데,

이걸 살짝 응용하면 될 것도 같은데. .....

https://sir.kr/qa/96995

답변 2개 / 댓글 4개

채택된 답변
+20 포인트
Copy
function drop_column($find, $position = 0) {
    $sql =" SELECT table_name FROM information_schema.tables where table_schema= `" . G5_MYSQL_DB . "`";
    $result = sql_query($sql);
    $report = '';
    while ($row = sql_fetch_array($result)) { 
        $sql_1 = ' describe ' . $row['table_name'];
        $result_1 = sql_query($sql_1);
        while ($row_1 = sql_fetch_array($result_1)) {
            $flag = false;
            switch ($position) {
                case 1:
                    $flag = strpos($row_1['Field'], $find) === 0;
                    break;
                case 2: 
                    $flag = substr($row_1['Field'], - strlen($find)) == $find;              
                    break;
                case 0:                
                    $flag = strpos($row_1['Field'], $find) !== false;
                break;
            }
            if ($flag) {
                $sql = " ALTER TABLE `{$row['table_name']}` DROP COLUMN  `{$row_1['Field']}` ";
                if (sql_query($sql))
                    $report .= $row['table_name'] . ' : ' . $row_1['Field'] . '<br>';
            }
        }  
    }
    return $report;
}

/**
* drop_column('검색어', 찾는조건)  
* drop_column('검색어', 1) 접두어
* drop_column('검색어', 2) 접미어
* drop_column('검색어') 전체
*/
echo drop_column('sir_', 1);

답변에 대한 댓글 3개

헐, 자고 일어났더니.....엄청난 선물이..... ^^
매번 좋은 코드 선물 주셔서 감사합니다.
// 수정본
<?php
include_once('./_common.php');

function drop_column($find, $position = 0) {
$sql =" SELECT table_name FROM information_schema.tables where table_schema='" . G5_MYSQL_DB . "'";
$result = sql_query($sql, true);
$report = '';
while ($row = sql_fetch_array($result)) {
$sql_1 = ' describe ' . $row['table_name'];
$result_1 = sql_query($sql_1, true);
while ($row_1 = sql_fetch_array($result_1)) {
$flag = false;
switch ($position) {
case 1:
$flag = strpos($row_1['Field'], $find) === 0;
break;
case 2:
$flag = substr($row_1['Field'], - strlen($find)) == $find;
break;
case 0:
$flag = strpos($row_1['Field'], $find) !== false;
break;
}
if ($flag) {
$sql = " ALTER TABLE `{$row['table_name']}` DROP COLUMN `{$row_1['Field']}` ";
if (sql_query($sql, true))
$report .= $row['table_name'] . ' : ' . $row_1['Field'] . '<br>';
}
}
}
return $report;
}
/**
* drop_column('검색어', 찾는조건)
* drop_column('검색어', 1) 접두어
* drop_column('검색어', 2) 접미어
* drop_column('검색어') 전체
*/
echo drop_column('sir_', 1);
?>
방금 한방에 깨끗이 청소가 되었습니다.
덕분에 DB가 아주 깨끗해 졌습니다. ^^
감사해용. ( ^ ________ ^ ) ======b

알려주신 링크의 '왕계란'님의 답을 응용하는 개념으로 컬럼을 삭제하시려면

Alter table  테이블명 drop colunm 컬럼명 ;

명령이 있습니다.

https://www.w3schools.com/sql/sql_alter.asp

를 참고해보세요

답변에 대한 댓글 1개

sql 낱개 구문, php 반복 구문...다 ...공부 한 건데....
제 실력의 한계가 응용력 부족인지라..... ^^;;;

답변을 작성하려면 로그인이 필요합니다.