简体   繁体   中英

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. 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM