【发布时间】:2015-06-26 19:05:22
【问题描述】:
我想在我的存储过程中执行排序和过滤。
我为假期表创建表:
CREATE TABLE [dbo].[Holiday](
[HolidaysId] [int] IDENTITY(1,1) NOT NULL,
[HolidayDate] [date] NULL,
[HolidayDiscription] [nvarchar](500) NULL,
[Name] [nvarchar](max) NULL,
CONSTRAINT [PK_Holiday] PRIMARY KEY CLUSTERED
(
[HolidaysId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我的过滤条件如下:
- 开始于
- 等于
- 不等于。
注意:过滤器比较时请忽略HolidayId。
我的餐桌:假期
HolidaysId int,Name nvarchar(500),HolidayDate date.
示例输入:
HolidayId Name Date
1 abc 1/1/2015
2 pqr 1/2/2015
3 xyz 1/3/2015
输出:
Case 1:Starts with(This is just for name column only.likewise i want to do for HolidayDate column too)
Input:ab(filtering parameter)
Query:where Name like '%ab%' order by Name(when sort column name is passed as parameter in stored procedure for column to sort(for eg:Name))
output:1,abc,1/1/2015
Case 2:Is Equal to(Same as above)
Input:prr(filtering parameter)
output:2,pqr,1/2/2015
Case 3:Not Equal to(Same as above)
Input:bbb(filtering parameter)
output:All Records
这是我目前的存储过程:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_PagedItems]
(
@Page int,
@RecsPerPage int
)
AS
-- We don't want to return the # of rows inserted
-- into our temporary table, so turn NOCOUNT ON
SET NOCOUNT ON
--Create a temporary table
CREATE TABLE #TempItems
(
ID int,
Name varchar(50),
HolidayDate date
)
-- Insert the rows from tblItems into the temp. table
INSERT INTO #TempItems (ID, Name,HolidayDate)
SELECT HolidaysId,HolidayDiscription,HolidayDate FROM holiday
-- Find out the first and last record we want
DECLARE @FirstRec int, @LastRec int
SELECT @FirstRec = (@Page - 1) * @RecsPerPage
SELECT @LastRec = (@Page * @RecsPerPage + 1)
-- Now, return the set of paged records, plus, an indiciation of we
-- have more records or not!
SELECT *,
MoreRecords =
(
SELECT COUNT(*)
FROM #TempItems TI
WHERE TI.ID >= @LastRec
)
FROM #TempItems
WHERE ID > @FirstRec AND ID < @LastRec
-- Turn NOCOUNT back OFF
SET NOCOUNT OFF
现在我要发送到我的存储过程的 4 件事是:
- 页码
- PageSize(要检索的记录数)
- 排序列名称(名称或假日日期)
- 我的过滤器列名(假日日期的名称)和运算符,如 StartWith 或等于或不等于。(列名和运算符)
谁能帮我执行排序和过滤,如果有任何与性能优化相关的更改,请给我建议。
【问题讨论】:
-
我不确定您要在这里实现什么,我认为一些示例数据和预期结果可能会有所帮助。将整个表放入临时表然后使用它似乎也很奇怪。为什么不只使用原始表?最后,you should not prefix your stored procedures with
sp_ -
请编辑您的问题,以使预期的输出更加清晰。
-
您是否在数据库上设置了任何索引?
-
@GarethD:请查看我更新的问题
-
但是您的存储过程不采用任何与您描述的过滤或排序相关的参数...如果没有它,您希望如何过滤数据?顺便提一句。将整个 Holiday 表插入 temp 表只是浪费内存和电力 - 只有在插入前过滤数据时,这样的操作才有意义。
标签: sql sql-server select stored-procedures sql-server-2008-r2