пʼятниця, 16 липня 2010 р.

MSSQL sort and filter procedure

Припустимо в нас є табличка:

CREATE TABLE [TestTable](
[ID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Size] [int] NULL,
[Created] [datetime] NULL
)

Для сортування і фільтрації по всіх полях можна використати процедуру:

CREATE PROCEDURE [TestTable_GetPagedAndSorted]
(
@startRowIndex int,
@maximumRows int,
@order nvarchar(50)
)
AS
BEGIN

declare @lastKey int
declare @lastAsc sql_variant
declare @lastDesc sql_variant

set rowcount @startRowIndex

select
@lastAsc = OrderAsc,
@lastDesc = OrderDesc,
@lastKey = OrderKey
from
(
select *,
ID as OrderKey,
case @order
when 'ID' then cast(ID as sql_variant)
when 'Name' then cast(Name as sql_variant)
when 'Size' then cast(Size as sql_variant)
when 'Created' then cast(Created as sql_variant)
else ID
END as OrderAsc,
case @order
when 'ID DESC' then cast(ID as sql_variant)
when 'Name DESC' then cast(Name as sql_variant)
when 'Size DESC' then cast(Size as sql_variant)
when 'Created DESC' then cast(Created as sql_variant)
END as OrderDesc
from TestTable
) as T
order by OrderAsc,OrderDesc desc,OrderKey

set rowcount @maximumRows

select *
from
(
select *,
ID as OrderKey,
case @order
when 'ID' then cast(ID as sql_variant)
when 'Name' then cast(Name as sql_variant)
when 'Size' then cast(Size as sql_variant)
when 'Created' then cast(Created as sql_variant)
else ID
END as OrderAsc,
case @order
when 'ID DESC' then cast(ID as sql_variant)
when 'Name DESC' then cast(Name as sql_variant)
when 'Size DESC' then cast(Size as sql_variant)
when 'Created DESC' then cast(Created as sql_variant)
END as OrderDesc
from TestTable
)as T
where
(
@lastAsc is null
and
@lastDesc is null
and
@lastKey is null
)
or
(
@lastAsc is not null
and
(
OrderAsc > @lastAsc
or
OrderAsc = @lastAsc
and
OrderKey > @lastKey
)
)
or
(
@lastDesc is not null
and
(
OrderDesc < @lastDesc
or
OrderDesc = @lastDesc
and
OrderKey > @lastKey
)
)
order by OrderAsc,OrderDesc desc,OrderKey

set rowcount 0

END

Немає коментарів:

Дописати коментар