May 27, 2015

SQL Server selecting from literal values

Filed under: sql server Himanshu @ 11:40 am

I didn’t knew it as possible to do this in SQL Server:

select * from (values (1, 2), (3, 4), (5, 6)) AS Numbers (Odds, Evens)

Parking it here for my later reference. Can be handy to insert couple of rows into some meta tables like:

declare @external_internal_state_map table (external_state_code varchar(6), internal_state_code varchar(6))
insert into @external_internal_state_map (external_state_code, internal_state_code) values
(‘EXT1’, ‘INT1’), (‘EXT2’, ‘INT2’), (‘EXT3’, ‘INT3’)
select * from @external_internal_state_map

August 5, 2008

Paging of SQL Server records

Filed under: .net,sql server Himanshu @ 6:29 am

In one of my ASP.NET, SQL Server project, we were expected to provide paging in the ASP.NET GridView. Microsoft’s very common sample will do this using Dataset filled with all records. If someone is doing GridView paging, s/he is doing it not waste server’s or client’s precious resources, Isn’t it?

To me, it make more sense to do paging of records being fetched in server memory along with view paging. What if table in question has more then 100,000 (1 lack) records?

Digging a bit further, I found a resource which explains how to do paging of records being sent from stored procedure. But it was expecting to have auto identity as primary key in the table. And we were so fortunate that we couldn’t have db design such that we can afford to have auto identity primary key, and so that solution to the paging problem. On doing some more finding, we all agreed to a solution that is described below. It’s not fully optimized, as it do not have any optimization for SQL Server to prepare result sets. But worked for our need in specific project as even in 100,000 records it was working very fast.

In our solution, stored procedure that will fetch records from table and return to caller will needs to have two addition parameters, @RowIndexFrom and @RowIndexTo

Getting customers by page will look like following,

CREATE PROCEDURE [dbo].[GetCustomersPage]
(
    @RowIndexFrom int,
    @RowIndexTo int
)
AS
BEGIN
    SET NOCOUNT ON;

    WITH IndexedCustomers AS
    (
        SELECT
            ROW_NUMBER() OVER (ORDER BY Id) AS rowIndex,
            Customers.*
        FROM
            Customers
    )
    SELECT * FROM IndexedCustomers WHERE rowIndex BETWEEN @RowIndexFrom AND @RowIndexTo

    SELECT COUNT(*)
    FROM
        Customers
END
GO

 

The stored procedure returns two result set, first will be records for given page (defined by different between @RowIndexFrom and @RowIndexTo parameters). And the second result set will give total number of records for give query. Second result set will help preparing pages list. So, if first page needs to be retrieved of page size 10, parameter values should be 1 and 10 respectively.

Powered by WordPress