如何通过动态传递表名来获取行计数

时间:2012-09-05 13:49:54

标签: sql count row

create procedure qa_cc
@tablename varchar(500)

AS 

BEGIN
    -- Create two integer values
DECLARE @tableOneCount varchar(50), @tableTwoCount varchar(50)

-- Get the number of rows from the first table
SELECT @tableOneCount = 'SELECT COUNT(*) FROM'  + @tablename; 
    exec (@tableOneCount);           

select      @tableOneCount  ; 

END

exec qa_cc @tablename=table1

4 个答案:

答案 0 :(得分:3)

SELECT SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 and ta.name=@tablename
 GROUP BY ta.name

请参阅http://blog.sqlauthority.com/2010/09/08/sql-server-find-row-count-in-table-find-largest-table-in-database-part-2/

答案 1 :(得分:2)

您可以使用sp_executesql,例如:

declare @sql nvarchar(max);
set @sql = N'select @cnt = count(*) from ' + @tablename;
declare @cnt int;
exec sp_executesql @sql, N'@cnt int output', @cnt = @cnt output;
select @cnt;

答案 2 :(得分:1)

在FROM关键字读取FROMTABLE而非FROM Table

之后,您似乎错过了一个空格
DECLARE @TABLE NVARCHAR(100)
SET @TABLE = 'CLIENT' -- YOUR TABLE NAME

EXEC('SELECT COUNT(*) FROM ' + @TABLE)

答案 3 :(得分:-1)

CREATE PROCEDURE [dbo].[TableRowCount]
@tableName text
AS
EXEC ('SELECT COUNT(*) FROM ' + @tableName)
RETURN @@ROWCOUNT

我希望有所帮助。谢谢。