I need to write some code that applies to only certain fields within our database. Specifically I'm looking for any field in all tables of a single database that are of type DECIMAL(12,5);
If it's of any help, all of our decimal fields are prefixed with dec_. I could gather all of the decimal fields from all tables, but there are tons of them that don't match my particular criteria, I need only the decimal values who's limit is 12,5.
I'd have no preference between doing this in pure SQL, or using PHP. We're currently using the CakePHP framework to manage our project, though I could just as easily do this without using the framework. This is a one time operation to gather the required data so I can continue forward with the audit.
Any help is greatly appreciated, thank you for taking the time to read this.
[EDIT] Got some great answers here, thanks everyone! I probably should have mentioned this in my initial post, but is there any way I can also get the table name associated with each field?
You can list a table's columns with the mysqlshow db_name tbl_name command. The DESCRIBE statement provides information similar to SHOW COLUMNS .
You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.
We can verify the data in the table using the SELECT query as below. We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information.
How to list all tables that contain a specific column name in MySQL? You want to look for tables using the name of columns in them. SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA. COLUMNS WHERE COLUMN_NAME IN('column1', 'column2') AND TABLE_SCHEMA = 'schema_name';
SELECT
TABLE_NAME,
COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = 'db-name' AND
DATA_TYPE = 'decimal' AND
NUMERIC_PRECISION = 12 AND
NUMERIC_SCALE = 5
You can try to use the following approach:
$pdo = new PDO(...);
$sql = "select column_name from
information_schema.columns
where table_schema='$your_db' and table_name='?' and data_type = 'decimal(12,5)'";
foreach($pdo->query("SHOW TABLES;") as $table) {
$prepared = $pdo->prepare($sql);
$prepared->execute(array($table));
print_R($prepared->fetchAll()) ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With