'How to print a message of number of rows from a table variable name

I have to print out the number of rows when given only a variable named after the table and not the actual table name itself. Below is my attempt to make this work. It should print out to the message box of SQL Server "X" number of rows.

DECLARE @tableName AS VARCHAR(100)
SET @tableName = 'Tb_Offers' --Name of table i need to find the number of rows therin

DECLARE @rowCount AS INT --variable to store count of rows
SELECT @rowCount = COUNT(*) FROM @tableName

PRINT @rowCount --statement to print count to MS SQL message box. 



Solution 1:[1]

Never SELECT COUNT(*) FROM <anything>; to get a count. Try:

DECLARE @tableName sysname = N'Tb_Offers';

SELECT @rowCount = SUM(rows)
  FROM sys.partitions
  WHERE [object_id] = OBJECT_ID(N'dbo.' 
    + QUOTENAME(@tableName))
  AND index_id IN (0,1);

Additionally:

  1. Object names are sysname or nvarchar(128), not varchar(100), and strings that contain entity names need to be prefixed with N. Use the system metadata correctly to avoid getting burned.
  2. Stop counting rows the hard way; there is zero reason to read an entire table to get the number of rows.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1