bgrossnickle (8/13/2013)
I am rying to run a TSQL SELECT Count(*) that has a @Tablename variable in it.My Tablename name needs to be variable and I will build it on the fly. All I want to know if if there is data in the table.
--Tried this but it did not work because of the @Database
Declare @Database varchar(20)
Set @Database = 'TDSTEP'
Declare @RowCount int
SELECT @RowCount = Count(*) FROM @Database
Print @RowCount
--Tried this but it did not work because of the @RowCount
Declare @Database varchar(20)
Set @Database = 'TDSTEP'
Declare @RowCount int
declare @SQL as varchar(max)
set @SQL = 'SELECT @RowCount = Count(*) FROM ' + @Database
exec (@SQL)
How can i get a variable TableName and yet interigate the number of rows returned?
Do you need this to use a variable for some reason?
You can do this with something like this.
Declare @Database varchar(20)
Set @Database = 'YourTableNameHere'
Declare @RowCount int
declare @SQL as varchar(max)
set @SQL = 'SELECT Count(*) FROM ' + @Database
declare @MyCount table(MyRowCount int)
insert @MyCount
exec (@SQL)
select * from @MyCount
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/