Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When I need to do paging, I typically use a temporary table as well. You can use an output parameter to return the total number of records. The case statements in the select allow you to sort the data on specific columns without needing to resort to dynamic SQL.</p> <pre><code>--Declaration-- --Variables @StartIndex INT, @PageSize INT, @SortColumn VARCHAR(50), @SortDirection CHAR(3), @Results INT OUTPUT --Statements-- SELECT @Results = COUNT(ID) FROM Customers WHERE FirstName LIKE '%a%' SET @StartIndex = @StartIndex - 1 --Either do this here or in code, but be consistent CREATE TABLE #Page(ROW INT IDENTITY(1,1) NOT NULL, id INT, sorting_1 SQL_VARIANT, sorting_2 SQL_VARIANT) INSERT INTO #Page(ID, sorting_1, sorting_2) SELECT TOP (@StartIndex + @PageSize) ID, CASE WHEN @SortColumn='FirstName' AND @SortDirection='ASC' THEN CAST(FirstName AS SQL_VARIANT) WHEN @SortColumn='LastName' AND @SortDirection='ASC' THEN CAST(LastName AS SQL_VARIANT) ELSE NULL END AS sort_1, CASE WHEN @SortColumn='FirstName' AND @SortDirection='DES' THEN CAST(FirstName AS SQL_VARIANT) WHEN @SortColumn='LastName' AND @SortDirection='DES' THEN CAST(LastName AS SQL_VARIANT) ELSE NULL END AS sort_2 FROM ( SELECT CustomerId AS ID, FirstName, LastName FROM Customers WHERE FirstName LIKE '%a%' ) C ORDER BY sort_1 ASC, sort_2 DESC, ID ASC; SELECT ID, Customers.FirstName, Customers.LastName FROM #Page INNER JOIN Customers ON ID = Customers.CustomerId WHERE ROW &gt; @StartIndex AND ROW &lt;= (@StartIndex + @PageSize) ORDER BY ROW ASC DROP TABLE #Page </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload