Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using variables in From Clause 1

Status
Not open for further replies.

Sunny4Ever

IS-IT--Management
Nov 6, 2002
77
GB
Hi all,

I was trying to write a query which will return the name of each user table in a database and the count of rows in each table.

--*********************************************************
DECLARE @MyTableName varchar(30)
DECLARE MyCursor CURSOR FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

OPEN MyCursor

FETCH NEXT FROM MyCursor INTO @MyTableName

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT COUNT(*) FROM @MyTableName
END

CLOSE MyCursor
DEALLOCATE MyCursor

--*********************************************************

But SQL 2000 returns the following error:

"Must declare the variable '@MyTableName'."

So it looks like you cannot use a variable in a FROM clause!! Any one have any information on this or ideas on how to get the end result?
 
You can't use table name as variable. You must do that in dynamic SQL:

Code:
DECLARE @MyTableName varchar(30)
DECLARE MyCursor CURSOR FOR 
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

OPEN MyCursor

FETCH NEXT FROM MyCursor INTO @MyTableName

WHILE @@FETCH_STATUS = 0
BEGIN
  exec ('SELECT COUNT(*) FROM ' + @MyTableName )
END

CLOSE MyCursor
DEALLOCATE MyCursor

"A long life is when each day is full and every hour wide!"
(A Jewish Mentor)
M. [hourglass]

 
This might be useful for you:

Code:
CREATE TABLE #tables (
	name sysname,
	rows int
)

INSERT #tables
EXEC sp_msforeachtable 'SELECT ''?'', COUNT(*) FROM ?'

SELECT * FROM #tables
ORDER BY name

--James
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top