To get total number of columns in a table in sql

后端 未结 9 1317
清酒与你
清酒与你 2021-01-30 13:05

I need a query in sql to get total columns in a table.Can anybody help?

相关标签:
9条回答
  • 2021-01-30 13:28

    In MS-SQL Server 7+:

    SELECT count(*)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'mytable'
    
    0 讨论(0)
  • 2021-01-30 13:29

    In my situation, I was comparing table schema column count for 2 identical tables in 2 databases; one is the main database and the other is the archival database. I did this (SQL 2012+):

    DECLARE @colCount1 INT;
    DECLARE @colCount2 INT;
    
    SELECT @colCount1 = COUNT(COLUMN_NAME) FROM MainDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
    SELECT @colCount2 = COUNT(COLUMN_NAME) FROM ArchiveDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
    
    IF (@colCount1 != @colCount2) THROW 5000, 'Number of columns in both tables are not equal. The archive schema may need to be updated.', 16;
    

    The important thing to notice here is qualifying the database name before INFORMATION_SCHEMA (which is a schema, like dbo). This will allow the code to break, in case columns were added to the main database and not to the archival database, in which if the procedure were allowed to run, data loss would almost certainly occur.

    0 讨论(0)
  • 2021-01-30 13:35

    You can try below query:

    select 
      count(*) 
    from 
      all_tab_columns
    where 
      table_name = 'your_table'
    
    0 讨论(0)
提交回复
热议问题