>USE AP > >DECLARE @DynamicSQL VARCHAR(max) >DECLARE @TableNameVar sysname >SELECT @TableNameVar = MIN(name) from sys.tables -- here we don't need dynamic SQL, we need to get the name of the table >SET @DynamicSQL = > 'SELECT COUNT(*) AS [Countof' + (@TableNameVar) + '] FROM ' + quotename(@TableNameVar) >--print (@DynamicSQL) -- we may want to use PRINT to debug the SQL >EXEC (@DynamicSQL) >>>
DECLARE @DynamicSQL VARCHAR(max) DECLARE @TableNameVar sysname SELECT @TableNameVar = MIN(name) from sys.tables -- here we don't need dynamic SQL, we need to get the name of the table SET @DynamicSQL = 'SELECT ' + quotename(@TableNameVar,'''') + ' as TableName, COUNT(*) AS [Countof' + (@TableNameVar) + '] FROM ' + quotename(@TableNameVar) --print (@DynamicSQL) -- we may want to use PRINT to debug the SQL EXEC (@DynamicSQL)If you want to get count of records for all tables in a database, it's easy as well - check my recent blog How to get information about all databases without a loop