Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find columns count of any table in any database from sql server master database?

Tags:

sql

sql-server

If I know the database-name and table-name, how can I find columns-count of the table from sql server master database?

What is the fastest way to find the columns count of any database-table?

What do you think about the performance of this query?

select count(*) from SYSCOLUMNS where id=(select id from SYSOBJECTS where name='Categories')

I need to support sql server 2000 and onwards.

like image 743
user366312 Avatar asked Dec 05 '09 12:12

user366312


People also ask

How do I find the number of columns in a table in SQL Server?

In the Microsoft SQL server, the DESC command is not an SQL command, it is used in Oracle. SELECT count(*) as No_of_Column FROM information_schema. columns WHERE table_name ='geeksforgeeks'; Here, COUNT(*) counts the number of columns returned by the INFORMATION_SCHEMA .

How do you get the count of all tables in a database?

To get the count of all the records in MySQL tables, we can use TABLE_ROWS with aggregate function SUM. The syntax is as follows. mysql> SELECT SUM(TABLE_ROWS) ->FROM INFORMATION_SCHEMA.


3 Answers

It may vary slightly depending on the version of SQL Server, but this will work for 2005:

SELECT
     COUNT(*)
FROM
     <database name>.sys.columns
WHERE
     object_id = OBJECT_ID('<database name>.<owner>.<table name>')

In 2000:

SELECT
     COUNT(*)
FROM
     <database name>.sysobjects o
INNER JOIN <database name>.syscolumns c ON
     c.id = o.id
WHERE
     o.name = '<table name>'

If you might have multiple tables with the same exact table name under different owners then you'll need to account for that. I forget the column name in sysobjects to look at off the top of my head.

UPDATE FOR NEWER VERSIONS OF SQL Server and ANSI compliance:

SELECT COUNT(*)
FROM
    <database name>.INFORMATION_SCHEMA.COLUMNS
WHERE
    TABLE_SCHEMA = '<table schema>' AND
    TABLE_NAME = '<table name>'
like image 115
Tom H Avatar answered Nov 02 '22 09:11

Tom H


You could (and should) do this - try to avoid using the "sysobjects" view - it's no longer supported and might be removed in SQL Server 2008 R2 or later.

Instead, use the "sys" catalog view in the database:

SELECT COUNT(*) 
FROM yourdatabase.sys.columns
WHERE object_id = OBJECT_ID('yourdatabase.dbo.tablename')

That should do the trick, and it's probably the easiest and fastest way to do it.

like image 29
marc_s Avatar answered Nov 02 '22 08:11

marc_s


How about

select count(*) from <database name.information_schema.columns where table_name = '<table_name>'
like image 34
Raj Avatar answered Nov 02 '22 08:11

Raj