Ottenere il numero di campi in un database con un'istruzione SQL?
Domanda
Come ottenere il numero di campi / voci in un database usando un'istruzione SQL?
Soluzione
mmm tutti i campi in tutte le tabelle? assumendo gli standard (mssql, mysql, postgres) è possibile inviare una query su information_schema.columns
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
O raggruppati per tabella:
SELECT TABLE_NAME, COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_NAME
Se più schemi hanno lo stesso nome di tabella nello stesso DB, DEVI includere anche il nome dello schema (ovvero: dbo.Books, user.Books, company.Books ecc.) Altrimenti otterrai risultati errati. Quindi la migliore pratica è:
SELECT TABLE_SCHEMA, TABLE_NAME, COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_SCHEMA, TABLE_NAME
Altri suggerimenti
prova questo, questo escluderà le viste, lascia la clausola where se vuoi le viste
select count(*) from information_schema.columns c
join information_schema.tables t on c.table_name = t.table_name
and t.table_type = 'BASE TABLE'
Sembra proprio questo ciò di cui hai bisogno.
select CountOfFieldsInDatabase = count(*)
from information_schema.columns
Solo per tutti gli altri lettori che stanno cercando su Google ...
Esistono diverse soluzioni non SQL, che potrebbero essere utili per l'utente. ecco 2 che uso.
Esempio 1: Accedi a VBA:
'Microsoft Access VBA
Function Count_Fields(Table_Name As String) As Integer
Dim myFieldCount As Integer
Dim db As DOA.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset(Table_Name, dbOpenDynaset)
myFieldCount = rs.Fields.Count
'return the count
Count_Fields = myFieldCount
'tidy up
Set rs = Nothing
Set db = Nothing
End Function
Esempio 2: PHP 5.1:
<?php
// PHP5 Implementation - uses MySQLi.
function countFields ($tableName) {
$db = new mysqli('myserver.me.com', 'user' ,'pass', 'databasename');
if(!$db) {
echo 'ERROR: Could not connect to the database.';
}
else {
$rs->$db->query("SELECT * FROM ".$tableName.");
$fieldCount = $rs->field_count;
}
return $fieldCount;
?>
scusa qualsiasi errore di battitura sopra - spero che qualcuno lo trovi utile
select count(column_name) from information_schema.columns
where table_name = **name of your table here **