tags:

views:

125

answers:

3

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.

+2  A: 

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.

Tom H.
But this post [http://www.codeproject.com/KB/database/RefactorTSQLs.aspx ] [Try not to use COUNT(*) to obtain the record count in the table] says that, your previous query doesn't always provide accurate result.
JMSA
count(*) is accurate, read the article again
blackanchorage
@TomH: your first query for SQL Server 2005 won't work, if you're in "master", and want to check a table from another database. You need to use `OBJECT_ID('<database>.<owner>.<table_name>')` for accurate results...
marc_s
@marc_s - Thanks, corrected it.
Tom H.
@JMSA - They are two totally different things. The query in the link that you provided was to get total *row* counts for a table using a single column value in sysindexes. That data can indeed become stale and be inaccurate. My query does an actual row count directly against the relevant table, which in this case happens to be a system table.
Tom H.
A: 

How about

select count(*) from <database name.information_schema.columns where table_name = '<table_name>'
Raj
+1  A: 

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.

marc_s
But does it support sql server 2000?
JMSA
No, that's for SQL Server 2005 and up - you didn't mention SQL Server 2000 in your post.......
marc_s
Sorry for that. But I need a query that supports sql server 2000 and onwards.
JMSA