Select Table Row Counts as Columns
Written by
Gregory Scot Collins
Monday, 31 December 2007, 8:49 AM
This article has been tested to work with the following products and versions. No guarantee of compatibility, with or without modification, is offered for products or versions other than those listed.
- SQL Server 2005 (Microsoft)
IN THIS ARTICLE:
If there is a need to identify the number of rows in one or more tables of your SQL database, you can easily get these counts and return them as columns of a SELECT clause. In this article, we will show the basic syntax required for achieving this, and then show an actual example using the AdventureWorks sample database.
Syntax for selecting table row counts as columns
The method of selecting table row counts as columns is simple and straighforward. Listing 1 shows the syntax as performing selects within your main SELECT clause. These inner-SELECT clauses must be contained within parentheses. The COUNT(*) function returns the number of rows in the specified table. The highlighted portions of Listing 1 identify places where you need to substitute in your actual table names and your desired resulting column names.
Selecting row counts using the AdventureWorks sample database
Now we will apply the syntax to an actual SELECT clause using the AdventureWorks sample database that ships with Microsoft SQL Server 2005. If you do not have this sample database installed, you can install it following the instructions contained within the SQL Server online help. Listing 2 gets the counts of four different tables and names the columns appropriately.
The result of the SELECT clause in Listing 2 is shown in Screenshot 1. Any number of table row counts can be returned in this manner.
Copyright ©2007
Braintrove. All rights reserved. This material may not be copied, published, broadcast, rewritten
or redistributed. You may, however, use the techniques, along with any associated code and files in
your development. This material is provided "AS IS" without warranty of any kind. You accept full
responsibility and liability for any and all results associated with use of this material.

Stumble It!
Digg It!
del.icio.us




