How do I count the number of rows a stored procedure would return the fastest way. Stored procedure returns rows around 100K to 1M records.
Select @@rowcount:
SELECT @@ROWCOUNT;
After executing the stored procedure.
So far the only thing that has worked for me is to:
a. Modify momentarily the stored procedure to dump the resulting dataset into a table. If changing the stored procedure is not an option replace Alter Procedure with Declare and remove the end, provide parameter values if not optional and execute as a query dumping the dataset into a table.
b. Script the table and drop it using SSMS.
c. Use the script to create a virtual table in the query and use Insert into with exec stored procedure to populate it.
d. Count the records.
I have a similar task with a restriction that I must not alter the SP to get the count. Hence:
sp_configure 'show advanced options', 1;
reconfigure;
go
sp_configure 'ad hoc distributed queries', 1;
reconfigure;
go
select count(*) from
openrowset('SQLOLEDB','Data Source=localhost;Trusted_Connection=yes;
Integrated Security=SSPI','exec DBNAME..SPName')
Another way to get the same result
CREATE PROCEDURE NOMBRE_PROCEDIMIENTO
as
BEGIN
if EXISTS (SELECT * from NOMBRE_TABLA WHERE CONDITIONS HERE)
BEGIN
SELECT @@ROWCOUNT
END
END
You can define output variable:
create procedure x
(@p1 int output)
as
select @p1 = count(*)
from Table
The answer is to use @@ROWCOUNT is still valid, but I would not recommend to run in directly after EXEC
like on existing answer.
SELECT
statement is not always the last statement is stored procedure or you could have multiple SELECT
statements:
Scenario:
CREATE PROCEDURE p
AS
BEGIN
CREATE TABLE #t(i INT);
INSERT INTO #t(i) VALUES (1),(2);
SELECT i FROM #t;
DROP TABLE IF EXISTS t;
END
EXEC p;
-- i
-- 1
-- 2
SELECT @@ROWCOUNT;
-- 0 instead of 2
db<>fiddle demo
One way is to use output parameter(as many as stored procedure resultset):
CREATE PROCEDURE p(@cnt INT OUT)
AS
BEGIN
CREATE TABLE #t(i INT);
INSERT INTO #t(i) VALUES (1),(2);
SELECT i FROM #t;
SET @cnt = @@ROWCOUNT; -- immediately after SELECT
DROP TABLE IF EXISTS t;
END
DECLARE @i INT;
EXEC p2 @cnt = @i OUT;
SELECT @i;
-- 2
db<>fiddle demo