user317891
user317891

Reputation: 23

how do find the number of rows in a table when the table name is in a variable?

The following is not working :(

Select @CurrentTableName = TableName from @tempTableNames Where ID = @ID  
Select @NumberOfColumns = SELECT count(*) FROM information_schema.columns WHERE table_name = @CurrentTableName
Select @SqlStmt = 'SELECT count(*) FROM ' + @CurrentTableName
Select @NumberOfRwos = exec @SqlStmt

Upvotes: 1

Views: 181

Answers (1)

Thomas
Thomas

Reputation: 64645

Declare @Count int
Declare @Sql nvarchar(4000)
Set @Sql = 'Select @Count = Count(*) From ' + Quotename(@CurrentTableName)

exec sp_executesql @SQL, N'@Count int OUTPUT', @Count OUTPUT

Select @Count...

Upvotes: 2

Related Questions