Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Getting row count as part of DB design info
Message
 
 
To
04/02/2008 11:04:54
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01289085
Message ID:
01289087
Views:
13
This message has been marked as a message which has helped to the initial question of the thread.
Rollin,

Please check http://www.mssqlcity.com/Articles/KnowHow/RowCount.htm

or

http://www.databasejournal.com/features/mssql/article.php/3441031

Look also to SP_MSForEachTable

http://www.databasejournal.com/features/mssql/article.php/1490661
use MyDatabase
go 
create table #rowcount (tablename varchar(128), rowcnt int)
exec sp_MSforeachtable 
   'insert into #rowcount select ''?'', count(*) from ?'
select top 5 * from #rowcount
    order by tablename
drop table #rowcount
>I am trying to create a DB design document for a legacy DB. Part of this is the row count of each table. I have put together the following query, but it chokes at the line indicated (inside the cursor).
>
> Msg 1087, Level 15, State 2, Line 44
> Must declare the table variable "@TableName".
>
>All help is always appreciated.
>
>Line of error:
>
>  	SET @RowCount = (SELECT COUNT (*) FROM @TableName)
>
>
>Whole code:
>
>USE MyDB
>GO
>DECLARE @TableName	VARCHAR(256),
>		@RowCount	INT
>
>DROP TABLE [dbo].[#MyDBTableInfo]
>
>CREATE TABLE #MyDBTableInfo (
>	MyDBTableInfoID			INT IDENTITY (1,1) PRIMARY KEY,
>	TableName					VARCHAR(256),
>	TableRowCount				SMALLINT,
>	COLUMN_NAME					VARCHAR(128),
>	ORDINAL_POSITION			INT,
>	COLUMN_DEFAULT				VARCHAR(4000),
>	DATA_TYPE					VARCHAR(128),
>	CHARACTER_MAXIMUM_LENGTH	INT,
>	NUMERIC_PRECISION			INT,
>	NUMERIC_PRECISION_RADIX		SMALLINT,
>	NUMERIC_SCALE				INT,
>	IS_NULLABLE					VARCHAR(3)
>)
>
>INSERT INTO #MyDBTableInfo
>SELECT
>	TABLE_SCHEMA + '.' + TABLE_NAME AS TableName,
>	0 AS TableRowCount,
>	COLUMN_NAME,
>	ORDINAL_POSITION,
>	COLUMN_DEFAULT,
>	DATA_TYPE,
>	CHARACTER_MAXIMUM_LENGTH,
>	NUMERIC_PRECISION,
>	NUMERIC_PRECISION_RADIX,
>	NUMERIC_SCALE,
>	IS_NULLABLE
>FROM INFORMATION_SCHEMA.COLUMNS
>
>DECLARE MyDBTableInfoCUR CURSOR FOR
>SELECT DISTINCT TableName
>FROM #MyDBTableInfo
>OPEN MyDBTableInfoCUR
>FETCH NEXT FROM MyDBTableInfoCUR INTO @TableName
>WHILE @@FETCH_STATUS = 0
>BEGIN
>	SET @RowCount = (SELECT COUNT (*) FROM @TableName)
>
>	UPDATE #MyDBTableInfo
>		SET TableRowCount = @RowCount WHERE TableName = @TableName
>
>	FETCH NEXT FROM MyDBTableInfoCUR INTO @TableName
>END
>CLOSE MyDBTableInfoCUR
>DEALLOCATE MyDBTableInfoCUR
>
>
>SELECT * FROM #MyDBTableInfo
>
>
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform