忽略跳过/接受存储过程

时间:2018-04-20 09:47:15

标签: sql-server stored-procedures

数据库中存在大量存储过程。 有@skip和@take参数。 我可以使用此存储过程并禁用@take吗?我想有时选择所有行,但有时候@take行。我可以使用像' if else'用于禁用@take,(如果@take为null - 例如)并且没有重复主选择代码或没有重复此存储过程而没有@skip,@ take?

ALTER PROCEDURE ...
@Skip INT,
@Take INT
AS
BEGIN
SELECT col1, col2, ...
...
...
...
 FROM ...
 WHERE ... 
 ORDER BY ....

OFFSET @Skip ROWS 
FETCH NEXT @Take ROWS ONLY 

我想实现这样的目标(@skip,@take仅在传递时):

ALTER PROCEDURE ...
@Skip INT = null,
@Take INT = null
AS
BEGIN
SELECT col1, col2, ...
...
...
...
 FROM ...
 WHERE ... 
 ORDER BY ....
if (@skip IS NOT NULL AND @take IS NOT NULL)
    OFFSET @Skip ROWS 
    FETCH NEXT @Take ROWS ONLY 

1 个答案:

答案 0 :(得分:2)

接受默认NULL值并将@Skip@Take设置为0,并在省略参数时设置非常大的值。

ALTER PROCEDURE YourProcedure
    @Skip INT = NULL,
    @Take INT = NULL
AS
BEGIN

    IF @Skip IS NULL
        SET @Skip = 0

    IF @Take IS NULL
        SET @Take = 999999999

    SELECT
        YourColumn
    FROM
        YourTable
    ORDER BY
        SomeColumn
    OFFSET 
        @Skip ROWS 
    FETCH NEXT 
        @Take ROWS ONLY 

END

确保您的最大@Take值始终大于查询结果行。