SQL Server从select存储过程返回行数

时间:2016-11-08 14:12:03

标签: sql-server tsql

我使用此查询从表Customers获取页面和索引限制结果。例如:

如果@iStartIndex = 0且@iRowsPerPage = 10,则结果是从0到10的10行。

function LimitKeys($id) {        
    $field = document.getElementById($id);
    $value = $($field).val(); //if the value contains multiple e , or . the value is no longer valid and gives me blank
    console.log($value);
    $regex = /[^\d]/;

    $val = $value.replace($regex, "");// cant replace in blank
    console.log($val);
    //$($field).val($val);
}

$('.number-only').keypress(function (event) { //sinds it's on keypress it won't catch the paste of data.
    console.log(this.value);
    var regex = new RegExp("^[0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

我的问题是我还需要该查询中的所有行数。例如:如果有1000行,查询将只选择10行。我需要那10行,但我还需要知道结果中有多少行 - 在这种情况下是1000行。

我已经尝试过的是返回@@ ROWCOUNT,但它返回10,即上次查询的结果。 我还试图写一个单独的查询:

    SELECT 
        Name, LastName, City                       
        FROM Customers                                  
    OFFSET @iStartIndex ROWS
    FETCH NEXT @iRowsPerPage ROWS ONLY

以下我写了原始查询。

有没有办法返回行,还能在同一存储过程中返回行数作为标量值?

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找这样的东西。只需使用结果集返回总计。这种情况并不罕见,尤其是在SP和其他报告工具的SP中,为每条记录返回重复数据。

DECLARE @TotalCount INT=SELECT COUNT(*) FROM Customers  
SELECT 
    Name, LastName, City, TotalCount=@TotalCount                       
    FROM Customers                                  
OFFSET @iStartIndex ROWS
FETCH NEXT @iRowsPerPage ROWS ONLY
相关问题