Getting number of fields in a database with an SQL Statement?

和自甴很熟 提交于 2019-12-22 02:20:27

问题


How would I get the number of fields/entries in a database using an SQL Statement?


回答1:


mmm all the fields in all the tables? assuming standards (mssql, mysql, postgres) you can issue a query over information_schema.columns

  SELECT COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 

Or grouped by table:

  SELECT TABLE_NAME, COUNT(*) 
  FROM INFORMATION_SCHEMA.COLUMNS 
  GROUP BY TABLE_NAME

If multiple schemas has the same table name in the same DB, you MUST include schema name as well (i.e: dbo.Books, user.Books, company.Books etc.) Otherwise you'll get the wrong results. So the best practice is:

SELECT TABLE_SCHEMA, TABLE_NAME, COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
GROUP BY TABLE_SCHEMA, TABLE_NAME



回答2:


try this, this will exclude views, leave the where clause out if you want views

  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'



回答3:


Sounds like this is what you need.

select CountOfFieldsInDatabase = count(*)
from   information_schema.columns



回答4:


Just for any other readers who are googling...

There are several non-SQL solutions, that may be useful to the user.. here's 2 that I use.

Example 1: Access 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

Example 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;
?>

please excuse any typo's in the above - hope someone finds this useful




回答5:


select count(column_name) from information_schema.columns 
where table_name = **name of your table here **


来源:https://stackoverflow.com/questions/1033726/getting-number-of-fields-in-a-database-with-an-sql-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!