用于查找表中行数的存储过程

时间:2014-05-19 05:40:15

标签: sql sql-server-2008

在存储过程中,我传递一个表名作为输入变量。

我想用该存储过程返回此表的行数。

我尝试了类似的东西,但它不起作用:

declare @maxRowCount bigint
exec('set '+ @maxRowCount + ' =(select COUNT(1) from ' + @tableName + ')')

这是SQL Server 2008。

4 个答案:

答案 0 :(得分:1)

以下示例应该为您提供一些工具。

-- fully qualify your table name (this is probably an input value in your sproc?)
-- please note that I use system view master.sys.tables as an example table here
DECLARE @tablename NVARCHAR(MAX) = N'[master].[sys].[tables]';

-- build the sql statement that you will execute
DECLARE @sql NVARCHAR(MAX) = N'SELECT COUNT(*) FROM ' + @tablename;

-- create a variable to hold the number of rows later on
DECLARE @nrofrows BIGINT;

-- create a temp table to store the result of executing the sql statement
CREATE TABLE #temp (NrOfRows BIGINT);

-- insert the result of the execution of the sql statement into the temp table
INSERT INTO #temp
EXECUTE(@sql);

-- extract the number of rows from the temp table
SET @nrofrows = (SELECT NrOfRows FROM #temp);

-- check the result so you can test!
PRINT @nrofrows;

如果您想了解有关动态SQL的良好背景信息,请查看Erland Sommarskog文章The Curse and Blessings of Dynamic SQL

答案 1 :(得分:1)

你可以试试这个

CREATE PROCEDURE dbo.sp_selectcount
  @tablename NVARCHAR(200)
AS

DECLARE @cmd NVARCHAR (255)
SET @cmd = 'SELECT count(*) from ' + @tablename
EXEC sp_executesql @cmd

答案 2 :(得分:0)

您应该删除@maxRowCount周围的引号。

试试这个:

declare @maxRowCount bigint
exec('set @maxRowCount =(select COUNT(*) from ' + @tableName + ')')

exec('SELECT @maxRowCount = COUNT(*) from ' + @tableName)

<强>分析:

使用您尝试的查询,它将执行:

set blablabla = (select count(1) from MyTable)

删除引号:

set @maxRowCount = (select count(*) from MyTable)

答案 3 :(得分:0)

您可以尝试这样做。

declare @maxRowCount bigint(5)
exec('SELECT COUNT(*) INTO @maxRowCount FROM ' + @tableName)