Wednesday, March 21, 2012

Problem with sorting

I am trying to set up custom paging and sorting with my gridview. All is well but the sorting. The problem is with the stored procedure. If I pass in the value @.sortExpression as, for example "discussions_Posts.post_time", i does not sort it at all. But if I replace the @.sortExpression with discussions_Posts.post_time in the actual stored procedure, it gets sorted.

how do I sort this query with a input parameter with values like "discussions_Topics.topic_title" or something?


ALTER PROCEDURE discussions_GetTopicsSubSet
@.startRowIndex as int,
@.maximumRows as int,
@.sortExpression as nvarchar(50),
@.board_id as int
AS

DECLARE @.Topics TABLE
(RowNumber INT,
topic_id INT,
topic_title VARCHAR(50),
topic_replies INT,
topic_views INT,
topic_type INT,
topic_time DATETIME,
post_id int,
post_time DATETIME,
Topic_Author_UserName nvarchar(256),
Topic_Author_ID uniqueidentifier,
Post_Author_Username nvarchar(256),
Post_Author_ID uniqueidentifier)

--DECLARE @.TopicsFrom Datetime

--SELECT @.TopicsFrom = CASE @.TopicsDays WHEN '1' THEN DATEADD(day,-1,getdate()) WHEN '2' THEN DATEADD(day,-7,getdate()) WHEN '3' THEN DATEADD(day,-14,getdate()) WHEN '4' THEN DATEADD(month,-1,getdate()) WHEN '5' THEN DATEADD(month,-3,getdate()) WHEN '6' THEN DATEADD(month,-6,getdate()) WHEN '7' THEN DATEADD(year,-1,getdate()) ELSE DATEADD(year,-1,getdate()) END
-- populate the table CAST(getdate() as int)
INSERT INTO @.Topics
SELECT ROW_NUMBER() OVER (ORDER BY @.sortExpression), discussions_Topics.topic_id, discussions_Topics.topic_title, discussions_Topics.topic_replies, discussions_Topics.topic_views, discussions_Topics.topic_type,discussions_Topics.topic_time, discussions_Posts.post_id, discussions_Posts.post_time, user_1.UserName AS Topic_Author_Username,
user_1.UserId AS Topic_Author_ID, user_2.UserName AS Post_Author_Username, user_2.UserId AS Post_Author_ID
FROM discussions_Topics INNER JOIN
discussions_Posts ON discussions_Posts.post_id = discussions_Topics.topic_last_post_id INNER JOIN
aspnet_Users AS user_1 ON user_1.UserId = discussions_Topics.topic_poster INNER JOIN
aspnet_Users AS user_2 ON user_2.UserId = discussions_Posts.poster_id
WHERE (discussions_Topics.board_id = @.board_id AND
discussions_Topics.topic_type NOT LIKE '1' )

SELECT * from @.Topics
WHERE RowNumber BETWEEN @.startRowIndex AND (@.startRowIndex + @.maximumRows) - 1

Hi ,

Just like dynamic selecting of column names are not permitted by sql server you also can't use dynamic column sorting.

To get the feature that you want. You have to concatenate and create a dynamic query and then execute the query to get your desired result.

Happy Programming,
Anton

No comments:

Post a Comment