Find the number of columns in a table

前端 未结 19 2183
Happy的楠姐
Happy的楠姐 2020-11-27 11:13

It is possible to find the number of rows in a table:

select count(*) from tablename

Is it possible to find the number of columns in a tabl

相关标签:
19条回答
  • 2020-11-27 11:53

    Here is how you can get a number of table columns using Python 3, sqlite3 and pragma statement:

    con = sqlite3.connect(":memory:")    
    con.execute("CREATE TABLE tablename (d1 VARCHAR, d2 VARCHAR)")
    cur = con.cursor()
    cur.execute("PRAGMA table_info(tablename)")
    print(len(cur.fetchall()))
    

    Source

    0 讨论(0)
  • 2020-11-27 11:54
    SELECT count(*) FROM information_schema.`COLUMNS` C
    WHERE table_name = 'your_table_name'
    AND TABLE_SCHEMA = "your_db_name"
    
    0 讨论(0)
  • 2020-11-27 11:54

    Can get using following sql statement:

    select count(*) Noofcolumns from SYSCOLUMNS where id=(select id from SYSOBJECTS where name='table_name')
    
    0 讨论(0)
  • 2020-11-27 11:58

    A MySQL answer adapted slightly from the MSDN example for MySqlDataReader.GetValues:

    //assumes you've already created a connection, opened it, 
    //and executed a query to a reader
    
    while(reader.Read())
    {
        Object[] values = new Object[reader.FieldCount];
        int fieldCount = reader.GetValues(values);
    
        Console.WriteLine("\nreader.GetValues retrieved {0} columns.",   fieldCount);
        for (int i = 0; i < fieldCount; i++)
            Console.WriteLine(values[i]);
    }
    

    Using MySqlDataReader.FieldCount will allow you to retrieve the number of columns in the row you've queried.

    0 讨论(0)
  • 2020-11-27 11:59

    Or use the sys.columns

    --SQL 2005
    SELECT  *
    FROM    sys.columns
    WHERE   OBJECT_NAME(object_id) = 'spt_values'
    -- returns 6 rows = 6 columns
    
    --SQL 2000
    SELECT  *
    FROM    syscolumns
    WHERE   OBJECT_NAME(id) = 'spt_values'
    -- returns 6 rows = 6 columns
    
    SELECT  *
    FROM    dbo.spt_values
        -- 6 columns indeed
    
    0 讨论(0)
  • 2020-11-27 12:00
    SELECT COUNT(COLUMN_NAME) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE 
        TABLE_CATALOG = 'Database name' 
        AND TABLE_SCHEMA = 'dbo' 
        AND TABLE_NAME = 'table name'
    
    0 讨论(0)
提交回复
热议问题