Counting the number of rows returned by stored procedure

前端 未结 7 1697
礼貌的吻别
礼貌的吻别 2021-01-03 23:11

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.

相关标签:
7条回答
  • 2021-01-03 23:21

    Select @@rowcount:

    SELECT @@ROWCOUNT;
    

    After executing the stored procedure.

    0 讨论(0)
  • 2021-01-03 23:24

    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.

    0 讨论(0)
  • 2021-01-03 23:26

    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')
    
    0 讨论(0)
  • 2021-01-03 23:32

    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
    
    0 讨论(0)
  • 2021-01-03 23:33

    You can define output variable:

    create procedure x
        (@p1 int output)
    as
        select @p1 = count(*) 
        from Table
    
    0 讨论(0)
  • 2021-01-03 23:36

    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

    0 讨论(0)
提交回复
热议问题