Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add a row count limit to a query in existing stored procedure?

Say I have a stored proc that returns a number of rows but I want to limit the amount of rows using TOP or something else. Is it possible to do this dynamically without creating another stored proc to update an existing stored proc to do this?

so my sp could look like this:

create procedure [dbo].[myproc]
@param1 int
as
begin
 select sumthing
 from mytable
 where mycolumn=2
end

How can I add another param to this sp and make it optional to restrict the number of rows when I need this?

like image 906
user603007 Avatar asked Jan 21 '26 00:01

user603007


2 Answers

Like this:

create procedure [dbo].[myproc]
    @param1 int,
    @optionalRowcount int = 999999999999
as
begin
 select TOP(@optionalRowcount) sumthing
 from mytable
 where mycolumn=2
end
like image 186
RBarryYoung Avatar answered Jan 23 '26 02:01

RBarryYoung


The rowcount option is probably the simplest way to solve this for a SELECT scenario, but I did just notice on the MSDN page that rowcount may be deprecated in a future release for DELETE, INSERT, and UPDATE. So I'll post this alternative here in case it's useful for someone:

create procedure [dbo].[myproc]
@param1 int = null
as
begin
    if @param1 is null
        select * from myTable
    else
        select top (@param1) *
        from myTable 
end
like image 45
eddie.sholl Avatar answered Jan 23 '26 03:01

eddie.sholl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!