Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of "Set rowcount" in SQL

I am using "Set RowCount" in my Stored Procedures. I have one question, what is the scope of Set RowCount ? Consider the below SPs

 CREATE PROC Test
    AS 
        BEGIN

            SET ROWCOUNT 10
            ...........

            SET ROWCOUNT 0

        END


CREATE PROC Test2
AS 
    BEGIN


        ...........

        SET ROWCOUNT 0

    END


CREATE PROC Test3
AS 
    BEGIN

        SET ROWCOUNT 10
        ...........


    END


CREATE PROC Test4
AS 
    BEGIN

        SET ROWCOUNT 10
        SET ROWCOUNT 5
        ...........
        SET ROWCOUNT 0      

    END

Now in the above SPs, you must be seeing I have mismatched SetRowcount statements. So my question what if I forgot to add "Set RowCount 0" to my opening "Set RowCount N" statement. Is it neccessary ? Will it affect the executions of rest of the SPs in my application ?

like image 619
Rocky Singh Avatar asked Mar 21 '11 21:03

Rocky Singh


People also ask

What is the use of set Rowcount in SQL Server?

Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have been affected by the specified number of rows. This includes triggers. The ROWCOUNT option does not affect dynamic cursors, but it does limit the rowset of keyset and insensitive cursors.

What does Rowcount do in SQL?

Data manipulation language (DML) statements set the @@ROWCOUNT value to the number of rows affected by the query and return that value to the client.

How do you give Rowcount in SQL?

The ROWCOUNT Set Function causes the server to stop the query processing after the specified number of records is returned. One may limit the number of records returned by all subsequent SELECT statements within the session by using the keyword SET ROWCOUNT.

How do I find the number of rows in a resultset in SQL Server?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row. However, it can also be used to number records in different ways, such as by subsets.


1 Answers

Contrary to the accepted answer in the question linked to in the comments as far as I can see the scope rules for this are exactly the same as those for #temp table visibility. It propagates to child batches but when the batch exits it gets reset to the previous value.

CREATE PROC #bar
AS
SELECT * FROM sys.objects
EXEC ('SELECT * FROM sys.objects')
GO

CREATE PROC #foo
AS
SET ROWCOUNT 1

EXEC #bar
GO

SET ROWCOUNT 4
EXEC #foo /*Returns 2 resultsets with 1 row*/
EXEC #bar /*Returns 2 resultsets with 4 rows*/

DROP PROC #foo
DROP PROC #bar
like image 185
Martin Smith Avatar answered Sep 29 '22 01:09

Martin Smith