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

MSSQL paging + sorting + filtering


CREATE PROCEDURE [TestTable_GetPagedAndSortedAndFiltered]
(
@startRowIndex int,
@maximumRows int,
@order nvarchar(50),
@ID int = null,
@Name nvarchar(50) = null,
@Size int = null,
@From datetime = null,
@To datetime = null
)
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
where
((@ID is null) or (@ID = ID))
and
((@Name is null) or (Name like @Name))
and
((@Size is null) or (@Size = Size))
and
((@From is null) or (@From < Created))
and
((@To is null) or (dateadd(day,1,@To) > Created))
) 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
where
((@ID is null) or (@ID = ID))
and
((@Name is null) or (Name like @Name))
and
((@Size is null) or (@Size = Size))
and
((@From is null) or (@From < Created))
and
((@To is null) or (dateadd(day,1,@To) > Created))

)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

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

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