Evaluate My Stored Procedure For Paging, Filtering, And Sorting
Apr 28, 2008
This is for SQL Server 2000. The purpose of the procedure is to return a subset of a filtered and sorted result set. The subset, filter criteria, and sort column and sort direction can be set dynamically. It uses the rowcount technique for paging.
This would be used to drive an ASP.NET gridview which supports filtering of the data, paging, and sorting. Please let me know what improvements I can make or if you have an idea for a better solution. (I didn't put this in a vBulletin code block because personally I find two sets of scroll bars annoying, but I can if people think it's better).
CREATE PROCEDURE dbo.Books_GetFilteredSortedSubset
(
-- paging
@startRowIndex INT = 1,
@maximumRows INT = 999999,
-- set the unique key used to ensure the rows are sorted deterministically
SET @uniqueKey = 'title_id'
-- build the FROM table source used throughout this procedure
SET @tableSource = 'titles t
inner join publishers p on t.pub_id = p.pub_id'
-- build the WHERE search condition used to control filtering throughout this procedure
SET @searchCondition = '(1 = 1)'
IF @title IS NOT NULL
SET @searchCondition = @searchCondition + ' AND (title LIKE ''%' + @title + '%'')'
IF @type IS NOT NULL
SET @searchCondition = @searchCondition + ' AND (type LIKE ''' + @type + '%'')'
IF @price IS NOT NULL
SET @searchCondition = @searchCondition + ' AND (price = ' + CAST(@price AS NVARCHAR) + ')'
-- build the ORDER BY expression used to control the sorting throughout this procedure
SET @orderByExpression = @sortColumn + ' ' + @sortDirection
-- add uniqeKey to ORDER BY statement to ensure consistent ordering of results when @sortColumn is not unique
IF @sortColumn <> @uniqueKey
SET @orderByExpression = @orderByExpression + ', ' + @uniqueKey + ' ' + @sortDirection
-- Get the column value at the position specified by @startRowIndex when the results are sorted in the desired sort order
SET @sql = 'SET ROWCOUNT @rowcount; SELECT @start_row = ' + @sortColumn + ', @start_row_id = ' + @uniqueKey +
' FROM ' + @tableSource +
' WHERE ' + @searchCondition + ' ORDER BY ' + @orderByExpression
-- add sql to filter the results based on criteria passed in as parameters
SET @sql = 'SET ROWCOUNT @rowcount; ' +
'SELECT
t.title_id,
t.title,
t.price,
t.type,
p.pub_name,
p.city,
p.state,
p.country
FROM ' + @tableSource +
' WHERE (' + @searchCondition + ') AND '
-- add sql to control the starting row
IF @sortDirection = 'ASC'
SET @sql = @sql + '( (' + @sortColumn + ' > @start_row) OR (' +
@sortColumn + ' = @start_row AND ' + @uniqueKey + ' >= @start_row_id) )'
ELSE
SET @sql = @sql + '( (' + @sortColumn + ' < @start_row) OR (' +
@sortColumn + ' = @start_row AND ' + @uniqueKey + ' <= @start_row_id) )'
-- add sql to control the ordering of everything
SET @sql = @sql + ' ORDER BY ' + @orderByExpression
PRINT @sql
SET @parameters = '@rowcount INT, @start_row sql_variant, @start_row_id sql_variant'
Hi Everybady Currenctly I have facing a problem on how to create a stored procedure that able to filter the data and order it dynamically on selected row. does anyone know how to do that I have successfully create a stored procedure that able to order with any colume at any direction and select it from rownumber to another rownumber. But i have failed to add another function with is where claus to do filtering on the data after ordering and selection does anybody can give me a example about that? Thanks a lot
As I said above, how do I put sorting + paging in a stored procedure.My database has approximately 50000 records, and obviously I can't SELECT all of them and let GridView / DataView do the work, right? Or else it would use to much resources per one request.So I intend to use sorting + paging at the database level. It's going to be either hardcode SQL or stored procedures.If it's hardcode SQL, I can just change SQL statement each time the parameters (startRecord, maxRecords, sortColumns) change.But I don't know what to do in stored procedure to get the same result. I know how to implement paging in stored procedure (ROW_NUMBER) but I don't know how to change ORDER BY clause at runtime in the stored procedure.Thanks in advance.PS. In case "ask_Scotty", who replied in my previous post, http://forums.asp.net/thread/1696818.aspx, is reading this, please look at my reply on your answer in the last post. Thank you.
However it is not saving in visual srudio 2005. it is saying 'ambiguous column name ID' does anyone know why?CREATE PROCEDURE PagedResults_New (@startRowIndex int, @maximumRows int ) AS
--Create a table variable DECLARE @TempItems TABLE (ID int IDENTITY, ShortListId int ) -- Insert the rows from tblItems into the temp. table INSERT INTO @TempItems (ShortListId) SELECT Id FROM Shortlist SWHERE Publish = 'True' order by date DESC
-- Now, return the set of paged records SELECT S.*FROM @TempItems t INNER JOIN ShortList S ON t.ShortListId = S.Id
WHERE ID BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
I know this topic has been gone overed a bit but it just seems that no one has a really good answer.
What i need it to be able to be able to pass in which index row i want to go from and to, as weel a a token which corresponds to how it should be sorted.
The problem with the methods that i have seen to do this is that they all use a case statement to handle the sorting like the below;
Code Snippet
;WITH TotalSales AS (
SELECT CASE @OrderBy
WHEN 'UnitPrice' THEN ROW_NUMBER() OVER (ORDER BY UnitPrice)
WHEN 'OrderQty' THEN ROW_NUMBER() OVER (ORDER BY OrderQty)
WHEN 'CarrierTrackingNumber' THEN (ROW_NUMBER() OVER (ORDER BY CarrierTrackingNumber))
END AS RowNumber,
CarrierTrackingNumber,
UnitPrice,
OrderQty
FROM Sales.SalesOrderDetail
WHERE CarrierTrackingNumber LIKE '%F%'
)
SELECT *
FROM TotalSales
WHERE RowNumber between @StartIndex and @StartIndex + 9
At the begging this looks really good but it turns out that this is really slow. In fact it is about twice as slow as using the below dynamic SQL:
Code Snippet
SET @SafeOrderBy = CASE @OrderBy
WHEN 'UnitPrice' THEN 'UnitPrice'
WHEN 'OrderQty' THEN 'OrderQty'
WHEN 'CarrierTrackingNumber' THEN 'CarrierTrackingNumber'
END
SET @temp = N'
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY ' + @SafeOrderBy + ') AS RowNumber,
CarrierTrackingNumber,
UnitPrice,
OrderQty
FROM Sales.SalesOrderDetail
WHERE CarrierTrackingNumber LIKE ''%F%''
) SUB
WHERE SUB.RowNumber between ' + @StartIndexAlt + ' and ' + @StartIndexAlt + ' + 9'
EXEC sp_executesql @temp
Now for a whole heap of reasons I would like to avoid using dynamic SQL to do this but if the alternative means that my queries take twice as long i dont see i have much of a choice.
I am wondering if anyone has any practical ways of sorting and paging within SQL server 2005. I have seen plenty of different example and there seems to numerous ways of doing it but i was wondering if anyone has a method that they have been using that they know works in enterprise level solutions and will work in the majority of cases as a standard. The method that has stood out thus far is Common table expressions but I am not sure if this is the best or optimal approach and whether it will work in with dynamic sorting. Thanks
Hello, my table is clustered according to the date. Has anyone found an efficient way to page through 16 million rows of data? The query that I have takes waaaay too long. It is really fast when I page through information at the beginning but when someone tries to access the 9,000th page sometimes it has a timeout error. I am using sql server 2005 let me know if you have any ideas. Thanks I am also thinking about switch datavase software to something that can handle that many rows. Let me know if you have a suggestion on a particular software that can handle paging through 16 million rows of data.
Hello, I receive this error "Incorrect syntax near 'GetGalleryPaged'." I'm trying to use custom paging on a stored procedure. ....... Dim mySqlConn As New SqlConnection(ConnStr) Dim objDA As New SqlDataAdapter("GetGalleryPaged", mySqlConn) objDA.SelectCommand.Parameters.Add("@startRowIndex", SqlDbType.Int, 1) objDA.SelectCommand.Parameters.Add("@@maximumRows", SqlDbType.Int, 9) Dim objDS As New DataSet() Dim objPds As PagedDataSource = New PagedDataSource objDA.Fill(objDS, "Gallery") <<----error here mySqlConn.Close() objPds.DataSource = objDS.Tables(0).DefaultView objPds.AllowPaging = True....... ALTER PROCEDURE dbo.GetGalleryPaged ( @startRowIndex int, @maximumRows int)AS SELECT idgallery, g_picpath FROM ( SELECT idgallery, g_picpath, ROW_NUMBER() OVER (ORDER BY idgallery DESC) AS RowRank FROM Gallery ) AS GalleryWithRowNumber WHERE RowRank > @startRowIndex AND RowRank <= (@startRowIndex + @maximumRows) ORDER BY idgallery DESC cheers,imperialx
WHILE @@FETCH_STATUS = 0 and @Counter < @PageSize BEGIN set @Counter = @Counter + 1 FETCH NEXT FROM cro_fastread END
close cro_fastread deallocate cro_fastread ///////////////////////////////////////// my problem is the "FETCH" method can only get a row at one time, so there would be return many recordsets, how can I merge all the return recordset into one. thanks in advance!
I apologize in advance, but this post might get somewhat lengthy.
I'm new to the whole pagiong and sorting in SQL Server 2005, and I'm trying to get my SQL to perform in a certain way but can't seem to nail it just down. Hopefully someone can provide some insight or direction. Here's the scoop:
The gui sorts on any column chosen. For example, there's USER, ADDRESS, CITY, STATE, ZIP. The gui allows you to choose how many rows you wish to display per page. If there are 500 rows that meet the search criteria and you choose five pages, there should be 100 records per page. Here's the code:
INSERT INTO #RESULTS
SELECT PY.PaymentId
, PY.PayeeId
, PY.PartyAddressId
, PY.DistributionId
, PY.EntitlementId
, PY.DeliveryTypeEnumItemId
, PY.AccountPaymentId
, PY.ParentPaymentId
, PY.PaymentAmount
, PY.PaymentDate
, PY.PaymentStatusEnumItemId
, PY.PaymentStatusDate
, PY.ReleaseRunId
, PY.ReleaseDate
, PY.AccountTransactionLogId
, PY.AccountStatusEnumItemId
, PY.AccountStatusDate
, PY.AccountPaidAmount
, PY.ReconciledInd
, PY.UndeliverableInd
, PY.ReissueNote
, PY.CreateDate
, PY.CreateId
, PY.ModifiedDate
, PY.ModifiedId
, DS.Description
, AC.Description
, AC.AccountProvider
, AC.AccountId
, PT.Name
, PA.AddressLine1
, PA.AddressLine2
, PA.City
, PA.State
, PA.Zip5
, PA.Zip4
, PE.clm_no
, CM.clmnt_idno
FROM Payment PY (NOLOCK)
JOIN (SELECT DISTINCT
PY.AccountPaymentId,
ROW_NUMBER() OVER(ORDER BY PY.AccountPaymentId) AS RowNum
FROM Payment PY (NOLOCK)) AS SQ
ON (SQ.AccountPaymentId = PY.AccountPaymentId)
JOIN Distribution DS (NOLOCK)
ON (DS.DistributionId = PY.DistributionId)
JOIN Account AC (NOLOCK)
ON (AC.AccountId = DS.AccountId)
JOIN PartyAddress PA (NOLOCK)
ON (PA.PartyAddressId = PY.PartyAddressId)
JOIN Party PT (NOLOCK)
ON (PT.PartyId = PA.PartyId)
JOIN Payee PE (NOLOCK)
ON (PE.PayeeId = PY.PayeeId)
JOIN clm CM (NOLOCK)
ON (CM.clm_no = PE.clm_no)
WHERE RowNum BETWEEN (((@Page * @PageSize) - @PageSize) + 1) AND ((@Page * @PageSize) - @PageSize) + @PageSize
AND ((@PayeeName IS NULL) OR (PT.[Name] LIKE '%' + @PayeeName + '%'))
AND ((@AccountId IS NULL) OR (AC.AccountId = @AccountId))
AND ((@DistributionId IS NULL) OR (DS.DistributionId = @DistributionId))
AND ((@PaymentDate IS NULL) OR (PY.PaymentDate = DATEADD(day, DATEDIFF(day, 0, @PaymentDate), 0))) -- Ignores the time
AND ((@PaymentNumber IS NULL) OR (PY.AccountPaymentId = @PaymentNumber))
AND ((@IsReconciled IS NULL) OR (PY.ReconciledInd = @IsReconciled))
AND ((@AmountIssued IS NULL) OR (PY.PaymentAmount = @AmountIssued))
AND ((@AmountPaid IS NULL) OR (PY.AccountPaidAmount = @AmountPaid))
AND ((@IssueStatus IS NULL) OR (PY.PaymentStatusEnumItemId = @IssueStatus))
AND ((@AccountStatus IS NULL) OR (PY.AccountStatusEnumItemId = @AccountStatus))
ORDER BY AccountPaymentID
--GET A COUNT OF THE ROWS SELECTED
SELECT @TotalRows = Count(*)
FROM Payment PY (NOLOCK)
JOIN (SELECT DISTINCT
PY.PaymentId,
ROW_NUMBER() OVER(ORDER BY PY.PaymentId) AS RowNum
FROM Payment PY (NOLOCK)) AS SQ
ON (SQ.PaymentId = PY.PaymentId)
JOIN Distribution DS (NOLOCK)
ON (DS.DistributionId = PY.DistributionId)
JOIN Account AC (NOLOCK)
ON (AC.AccountId = DS.AccountId)
JOIN PartyAddress PA (NOLOCK)
ON (PA.PartyAddressId = PY.PartyAddressId)
JOIN Party PT (NOLOCK)
ON (PT.PartyId = PA.PartyId)
JOIN Payee PE (NOLOCK)
ON (PE.PayeeId = PY.PayeeId)
JOIN clm CM (NOLOCK)
ON (CM.clm_no = PE.clm_no)
WHERE
((@PayeeName IS NULL) OR (PT.[Name] LIKE '%' + @PayeeName + '%'))
AND ((@AccountId IS NULL) OR (AC.AccountId = @AccountId))
AND ((@DistributionId IS NULL) OR (DS.DistributionId = @DistributionId))
AND ((@PaymentDate IS NULL) OR (PY.PaymentDate = DATEADD(day, DATEDIFF(day, 0, @PaymentDate), 0))) -- Ignores the time
AND ((@PaymentNumber IS NULL) OR (PY.AccountPaymentId = @PaymentNumber))
AND ((@IsReconciled IS NULL) OR (PY.ReconciledInd = @IsReconciled))
AND ((@AmountIssued IS NULL) OR (PY.PaymentAmount = @AmountIssued))
AND ((@AmountPaid IS NULL) OR (PY.AccountPaidAmount = @AmountPaid))
AND ((@IssueStatus IS NULL) OR (PY.PaymentStatusEnumItemId = @IssueStatus))
AND ((@AccountStatus IS NULL) OR (PY.AccountStatusEnumItemId = @AccountStatus))
SET @ORDERBY = ' ORDER BY ' + @SORT --END
--CASE WHEN @Sort IS NULL THEN '' ELSE
EXEC('SELECT * FROM #RESULTS ' + @ORDERBY)
--SET @TOPSQL = 'SELECT TOP ' + Convert(VarChar,@PageSize) + '* FROM #RESULTS ' + @ORDERBY
--SELECT @TOPSQL
--EXEC (@TOPSQL)
SET @PAGES = Round(@totalRows / @PageSize,0,1) + CASE WHEN @TotalRows % @PageSize = 0 THEN 0 ELSE 1 END
-- Return Total number of pages and Total number of Rows
SELECT @PAGES AS PageCount,
@TOTALROWS AS TotalRecords
I get back the rows I'm expecting and it looks fine. What I can't get to happen is the proper sort.
I get back records 1014 records - 1001 through 2014. I choose to display 400 records per page, so ther will be 3 pages total (1001 through 1400 on page 1, 1401 through 1800 on page 2, and 1801 through 2014 on page 3. All the records are sorted by RECORD NUMBER (1000, 1001, etc.)
What I would like to do is when I choose to sort on the column (ASC or DESC),
1.) The entire record set is esssentially retrieved again,
2.) The record set is resorted in the proper order
3.) The record set is redisplayed.
For example, if I'm on Page 2, and I choose to sort in DESCending order, Page 1 would then have records 2014 through 1615, Page 2 would display 1614 through 1215, and page 3 would have 1214 through 1001. Since I was already on Page 2, I would be seeing Page 2 with the new sort. Now when I resort , it just sorts the records on the individual pages, not the entire result set.
Hopefully this all made sense...!
If anyone has any advice or insight, please don't hesitate!
I apologize in advance, but this post might get somewhat lengthy.
I'm new to the whole pagiong and sorting in SQL Server 2005, and I'm trying to get my SQL to perform in a certain way but can't seem to nail it just down. Hopefully someone can provide some insight or direction. Here's the scoop:
The gui sorts on any column chosen. For example, there's USER, ADDRESS, CITY, STATE, ZIP. The gui allows you to choose how many rows you wish to display per page. If there are 500 rows that meet the search criteria and you choose five pages, there should be 100 records per page. Here's the code:
Code Snippet INSERT INTO #RESULTS SELECT PY.PaymentId , PY.PayeeId , PY.PartyAddressId , PY.DistributionId , PY.EntitlementId , PY.DeliveryTypeEnumItemId , PY.AccountPaymentId , PY.ParentPaymentId , PY.PaymentAmount , PY.PaymentDate , PY.PaymentStatusEnumItemId , PY.PaymentStatusDate , PY.ReleaseRunId , PY.ReleaseDate , PY.AccountTransactionLogId , PY.AccountStatusEnumItemId , PY.AccountStatusDate , PY.AccountPaidAmount , PY.ReconciledInd , PY.UndeliverableInd , PY.ReissueNote , PY.CreateDate , PY.CreateId , PY.ModifiedDate , PY.ModifiedId , DS.Description , AC.Description , AC.AccountProvider , AC.AccountId , PT.Name , PA.AddressLine1 , PA.AddressLine2 , PA.City , PA.State , PA.Zip5 , PA.Zip4 , PE.clm_no , CM.clmnt_idno FROM Payment PY (NOLOCK) JOIN (SELECT DISTINCT PY.AccountPaymentId, ROW_NUMBER() OVER(ORDER BY PY.AccountPaymentId) AS RowNum FROM Payment PY (NOLOCK)) AS SQ ON (SQ.AccountPaymentId = PY.AccountPaymentId) JOIN Distribution DS (NOLOCK) ON (DS.DistributionId = PY.DistributionId) JOIN Account AC (NOLOCK) ON (AC.AccountId = DS.AccountId) JOIN PartyAddress PA (NOLOCK) ON (PA.PartyAddressId = PY.PartyAddressId) JOIN Party PT (NOLOCK) ON (PT.PartyId = PA.PartyId) JOIN Payee PE (NOLOCK) ON (PE.PayeeId = PY.PayeeId) JOIN clm CM (NOLOCK) ON (CM.clm_no = PE.clm_no) WHERE RowNum BETWEEN (((@Page * @PageSize) - @PageSize) + 1) AND ((@Page * @PageSize) - @PageSize) + @PageSize AND ((@PayeeName IS NULL) OR (PT.[Name] LIKE '%' + @PayeeName + '%')) AND ((@AccountId IS NULL) OR (AC.AccountId = @AccountId)) AND ((@DistributionId IS NULL) OR (DS.DistributionId = @DistributionId)) AND ((@PaymentDate IS NULL) OR (PY.PaymentDate = DATEADD(day, DATEDIFF(day, 0, @PaymentDate), 0))) -- Ignores the time AND ((@PaymentNumber IS NULL) OR (PY.AccountPaymentId = @PaymentNumber)) AND ((@IsReconciled IS NULL) OR (PY.ReconciledInd = @IsReconciled)) AND ((@AmountIssued IS NULL) OR (PY.PaymentAmount = @AmountIssued)) AND ((@AmountPaid IS NULL) OR (PY.AccountPaidAmount = @AmountPaid)) AND ((@IssueStatus IS NULL) OR (PY.PaymentStatusEnumItemId = @IssueStatus)) AND ((@AccountStatus IS NULL) OR (PY.AccountStatusEnumItemId = @AccountStatus)) ORDER BY AccountPaymentID --GET A COUNT OF THE ROWS SELECTED SELECT @TotalRows = Count(*) FROM Payment PY (NOLOCK) JOIN (SELECT DISTINCT PY.PaymentId, ROW_NUMBER() OVER(ORDER BY PY.PaymentId) AS RowNum FROM Payment PY (NOLOCK)) AS SQ ON (SQ.PaymentId = PY.PaymentId) JOIN Distribution DS (NOLOCK) ON (DS.DistributionId = PY.DistributionId) JOIN Account AC (NOLOCK) ON (AC.AccountId = DS.AccountId) JOIN PartyAddress PA (NOLOCK) ON (PA.PartyAddressId = PY.PartyAddressId) JOIN Party PT (NOLOCK) ON (PT.PartyId = PA.PartyId) JOIN Payee PE (NOLOCK) ON (PE.PayeeId = PY.PayeeId) JOIN clm CM (NOLOCK) ON (CM.clm_no = PE.clm_no) WHERE ((@PayeeName IS NULL) OR (PT.[Name] LIKE '%' + @PayeeName + '%')) AND ((@AccountId IS NULL) OR (AC.AccountId = @AccountId)) AND ((@DistributionId IS NULL) OR (DS.DistributionId = @DistributionId)) AND ((@PaymentDate IS NULL) OR (PY.PaymentDate = DATEADD(day, DATEDIFF(day, 0, @PaymentDate), 0))) -- Ignores the time AND ((@PaymentNumber IS NULL) OR (PY.AccountPaymentId = @PaymentNumber)) AND ((@IsReconciled IS NULL) OR (PY.ReconciledInd = @IsReconciled)) AND ((@AmountIssued IS NULL) OR (PY.PaymentAmount = @AmountIssued)) AND ((@AmountPaid IS NULL) OR (PY.AccountPaidAmount = @AmountPaid)) AND ((@IssueStatus IS NULL) OR (PY.PaymentStatusEnumItemId = @IssueStatus)) AND ((@AccountStatus IS NULL) OR (PY.AccountStatusEnumItemId = @AccountStatus)) SET @ORDERBY = ' ORDER BY ' + @SORT --END --CASE WHEN @Sort IS NULL THEN '' ELSE EXEC('SELECT * FROM #RESULTS ' + @ORDERBY) --SET @TOPSQL = 'SELECT TOP ' + Convert(VarChar,@PageSize) + '* FROM #RESULTS ' + @ORDERBY --SELECT @TOPSQL --EXEC (@TOPSQL) SET @PAGES = Round(@totalRows / @PageSize,0,1) + CASE WHEN @TotalRows % @PageSize = 0 THEN 0 ELSE 1 END -- Return Total number of pages and Total number of Rows SELECT @PAGES AS PageCount, @TOTALROWS AS TotalRecords
I get back the rows I'm expecting and it looks fine. What I can't get to happen is the proper sort.
I get back records 1014 records - 1001 through 2014. I choose to display 400 records per page, so ther will be 3 pages total (1001 through 1400 on page 1, 1401 through 1800 on page 2, and 1801 through 2014 on page 3. All the records are sorted by RECORD NUMBER (1000, 1001, etc.)
What I would like to do is when I choose to sort on the column (ASC or DESC),
1.) The entire record set is esssentially retrieved again, 2.) The record set is resorted in the proper order 3.) The record set is redisplayed.
For example, if I'm on Page 2, and I choose to sort in DESCending order, Page 1 would then have records 2014 through 1615, Page 2 would display 1614 through 1215, and page 3 would have 1214 through 1001. Since I was already on Page 2, I would be seeing Page 2 with the new sort. Now when I resort , it just sorts the records on the individual pages, not the entire result set.
Hopefully this all made sense...!
If anyone has any advice or insight, please don't hesitate!
Hi, can anyone tell me how I can get implement sorting and paging using a recursive query? I have a created a stored procedure (bit like the simple example below), but would like to add in sorting and paging using order by and row_number(). DECLARE @CategoryID intSET @CategoryID = 12;WITH CTE_Example (CategoryID, CategoryName, ParentID, Depth, RowNum)AS(SELECT CategoryID, CategoryName, ParentID, 0 AS Depth, Row_Number() OVER (ORDER BY CategoryName) AS RowNumFROM Categories WHERE CategoryID = @CategoryIDUNION ALLSELECT Categories.CategoryID, Categories.CategoryName, Categories.ParentID, CTE_Example.Depth + 1 AS Depth, Row_Number() OVER (ORDER BY Categories.CategoryName) AS RowNumFROM CategoriesJOIN CTE_Example ON Categories.ParentID = CTE_Example.CategoryID)SELECT * FROM CTE_Example WHERE RowNum BETWEEN @Start AND @End ORDER BY RowNum I think the problem comes down to the Union, appreciate if someone can help. Many thanks, Matt
consider a stored procedure with a parameter @OrderID, i want to perform the following query :select * from Orders where OrderID = @OrderIDi want the condition to be true when parameter @OrderId is null so what is the syntax for that? i think there is an IF CONDITION that can be embedded with where clause.
I've made another topic before concerning this problem, but since it was really confusing, I will made one clearer (it was about orthodromic formula, in case you read it, but the problem change during the topic, so thats why im creating this new one too). I have a stored procedure with custom pagin method inside, and I want to sort my records on a fields I create myself (which will receive a different value for each record.) Now, I want to sort on this temporary field. And since this is a custom paging method I can choose between many page. Now, for the first page, it sorts fine. But when I choose a page above the first one, the sorting is not right (the results all are wrong). So my real question is: is it really possible to sort on a Temporary Field in a custom paging method (because I know I can do it without any problem on a real field from my table, it just doesnt work right when I try on a temporary field). I tried to solve my problem with this little SQL instruction, but it didnt give me any result yet: SELECT TOP 20 PK, test = field_value FROM Table WHERE PK not in (SELECT TOP 10 ad_id FROM Table ORDER BY ?) ORDER BY ? well thanks for taking the time to read this, any help woulb be appreciated.
User's requirement: use the SP get the dataset from DB at once. Want to make an accurate count of paging ( 200 rows /page) at the SSRS side. Need to provide sorting, user just need to click the according column header's caption.
The design is: we add group to devide the data into 200 per unit. Choice 'page break at end'. add 2 Report Parameters, SD & SF, means sorting direction and Field. In the Table Parameters add:
everything seems OK at this time, and the rpt is very quick.
The Bug is: Test team found out the sorting was broken by group, because we Choice 'page break at end'. Noe the sorting scope is just the first page (first group)
Help wants: query DB once , Accurate paging, full scope sorting.
Hi, I am trying to implement filtering on a custome paged stored Procedure, here is my curent Stored Procedure which doesn't error on complie or run but returns no records. Anyone got any ideas on how to make this work???<Stored Procedure>set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgo-- =============================================-- Author: Peter Annandale-- Create date: 22/10/2006-- Description: Get Filtered Names-- =============================================ALTER PROCEDURE [dbo].[proc_NAMEFilterPaged] -- Add the parameters for the stored procedure here @startRowIndex int, @maximumRows int, @columnName varchar(20), @filterValue varchar(20)ASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;SELECT CODE, LAST_NAME, Name, TYPE, NUMBER FROM (SELECT n.CODE, n.LAST_NAME, n.FIRST_NAME + ' ' + n.MIDDLE_NAME AS Name, nt.TYPE, f.NUMBER, ROW_NUMBER() OVER(ORDER BY n.LAST_NAME) as RowNum FROM dbo.NAME n LEFT OUTER JOIN NAMETYPE nt ON n.NAME_TYPE = nt.NAME_TYPE LEFT OUTER JOIN FUNERAL f ON n.CODE = f.DECEASED WHERE @columnName LIKE @filterValue ) as NameInfo WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) -1END </Stored Procedure> Any assistance would be greatly appreciated.. Regards..Peter.
Hello, I am looking at writing a SP without much success which enables multiple filtering on one field. Something like below: Input field: Product Description So if the user enters: "Large Drill" OR "Drill Large" the same resultset will be returned. SELECT * FROM products WHERE products.prod_desc contains both "Large" AND "Drill" I guess there'll need to be a nested Select and loop to parse the space separated input field. Any pointers would be appreciated. Thank you Lee
I have the following, which loads up a product search i now want to be able to sort it based on criteria such as price. This is what i have so far; String str = Session["subCategoryID"].ToString(); SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["streamConnectionString"].ConnectionString);SqlCommand command = new SqlCommand("stream_CategoryResults", conn); command.Parameters.Add("@subCategoryID", SqlDbType.Int).Value = str;command.CommandType = CommandType.StoredProcedure; conn.Open();SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); dgProducts.DataSource = reader; dgProducts.DataBind(); conn.Close(); My question is would i need to have different stored procedures, for when loading it up, and when sorting it by price. This is what my stored procedure looks like;CREATE PROCEDURE stream_CategoryResultsByPrice @subCategoryID INT AS SELECT DISTINCT Companies.companyName, Companies.companyLogo,SubCategories.subCategoryName, Products.productPrice, Products.productInfoURL FROM Companies INNER JOIN Products ON Companies.companyID = Products.companyID INNER JOIN SubCategories ON Products.subcategoryID = SubCategories.subCategoryID WHERE SubCategories.subCategoryID=@subCategoryID
Normally when I do a sort for a stored procedure I use something like this:
ORDER BY CASE WHEN @SortOrder = 'FirstName' THEN FirstName WHEN @SortOrder = 'LastName' THEN LastName WHEN @SortOrder = 'Extension' THEN Extension ELSE LastName
How do I get that into a dynamic SQL statement with proper quotes? Most of the SQL left out for cleanliness. The order by below would be the ELSE condition.
@SortValue varChar(30)= SHARE_DESCRIPTION as SELECT SHARES.SHARE_DESCRIPTION, SHARES.SHARE_SYMBOL, SECTORS.SECTOR_NAME FROM SHARES INNER JOIN SECTORS ON SHARES.SECTOR_ID = SECTORS.SECTOR_ID ORDER BY @SortValue but it does not seem to be possible to use variable after order by is there any way to achieve something with sorting by variable?
I have a stored procedure in my SQL 2005 Server database named Foo that accepts two parameters, @paramA and @paramB.In my ASP.NET page, I have these:<asp:GridView id="gv" runat="server" AutoGenerateColumns="true" DataSourceID="DS" AllowSorting="true" DataKeyNames="ID"/><asp:SqlDataSource ID="DS" runat="server" ConnectionString="<%$ ConnectionStrings:CS1 %>" SelectCommand="Foo" SelectCommandType="StoredProcedure" OnSelecting="DS_Selecting"> <asp:Parameter Name="paramA" Type="String" /> <asp:Parameter Name="paramB" Type="String" /></asp:SqlDataSource>In my setup, paramA and paramB are set in DS_Selecting(), where I can access the Command.Parameters[] of DS.Now, here's the problem. As you can see, the GridView allows for sorting. When you click on a header title to sort, however, the GridView becomes empty. My question is, how can I get the GV sorted and in the correct direction (i.e. asc/desc)? My first step in my attempt was to add another parameter to the SqlDataSource and sotred procedure Foo (e.g. @SortByColumn), then changed Foo appropriately: ALTER PROCEDURE Foo @paramA nvarchar(64), @paramB nvarchar(64), @SortColumn nvarchar(16) = 'SearchCount' AS SELECT * FROM Searches ORDER BY CASE WHEN @SortColumn='SearchCount' THEN SearchCount WHEN @SortColumn='PartnerName' THEN PartnerName ELSE ID ENDThat works find and dandy. But wait--I want to get the correct ORDER BY direction too! So I add another parameter to the SqlDataSource and Foo (@SortDirection), then alter Foo: ... SELECT * From Searchces ORDER BY CASE /* Keep in mind that CASE short-circuits */ WHEN @SortColumn='SearchCount' AND @SortDirection='desc' SearchCount DESC WHEN @SortColumn='SearchCount' SearchCount WHEN @SortColumn='PartnerName' AND @SortDirection='desc' PartnerName DESC WHEN @SortColumn='PartnerName' PartnerName WHEN @SortColumn='ID' AND @SortDirection='desc' ID DESC ELSE ID END ...But including DESC or ASC after the column name to sort by causes SQL to error. What the heck can I do, besides convert all my stored procedures into in-line statements inside the ASP page, where I could then dynamically construct the appropriate SQL statement? I'm really at a loss on this one! Any help would be much appreciated!Am I missing a much simpler solution? I am making this too complicated?
I want to sort a stored procedure based on a variable passed to it... what is the easiest way to do this? Here's an example of what I want to do:
sp_select_thing 10, 'thing_name', 'asc'
It would run the query then somehow evaluate parameters 2 and 3 to be placed in the ORDER BY clause. I'm not sure if they should be quoted as strings or not, I don't have an idea how to pass a "reference to a variable" as a parameter to a stored procedure... or even if such a thing is possible
I have a database of automobiles. I have many many columns, it is blank of course until I can start filling it with information. I will have four main rows. Yearnum, Make, Model, and VehicleStyle columns I will use Honda Accord as an example. Honda has made the Accord since probably the 80's I know that if I SELECT yearnum FROM YearNum ORDER BY yearnum
I am using C++ Builder too.. it will put all my years in order, in a combo box. But I believe it will also have duplicates, like for example They may have made a 1995 Honda Accord and then made a 1995 Honda accord LS which may have different wiring colors and speakers sizes than the regular accord. Is there anyway to filter out multiple years, so I could just have the regular order of years?
All I want to do is create a UDF that will evaluate these strings as math formula and return the value depending on the values of the other columns in the row.
Bear in mind that there may not be a string formula at all for some rows, in which case the value of teh Hours column alone should be the result.
I can do this in vb using the 'Replace' function but am having difficulty in translating it over to T-SQL.
Here is the vb version i use in Ms Access...
getFormula(strDutyType As String, dblTotalNumber As Double, dblWeightingAs Double, dblHours As Double, dblMinutes As String, strFormula As Variant)
If IsNull(strFormula) Or strFormula = "" Then getFormula = dblHours Exit Function End If
I am trying to use SSIS to update an AS400 DB2 database by calling a stored procedure on the AS400 using an OLE DB command object. I have a select statement running against the SQL Server 2005 that brings back 20 values, all of which are character strings, and the output of this select is piped into the OLE DB command object. The call from SSIS works just fine to pass parameters into the AS400 as long as the stored procedure being called does not have an output parameter defined in its signature. There is no way that I can find to tell the OLE DB command object that one of the parameters is an output (or even an input / output) parameter. As soon as one of the parameters is changed to an output type, I get an error like this:
Code Snippet
Error: 0xC0202009 at SendDataToAs400 1, OLE DB Command [2362]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x8000FFFF.
Error: 0xC0047022 at SendDataToAs400 1, DTS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED. The ProcessInput method on component "OLE DB Command" (2362) failed with error code 0xC0202009. The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running. There may be error messages posted before this with more information about the failure.
Error: 0xC0047021 at SendDataToAs400 1, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "WorkThread0" has exited with error code 0xC0202009. There may be error messages posted before this with more information on why the thread has exited.
Information: 0x40043008 at SendDataToAs400 1, DTS.Pipeline: Post Execute phase is beginning.
Information: 0x40043009 at SendDataToAs400 1, DTS.Pipeline: Cleanup phase is beginning.
Task failed: SendDataToAs400 1
Warning: 0x80019002 at RetrieveDataForSchoolInitiatedLoans: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
Warning: 0x80019002 at Load_ELEP: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "Load_ELEP.dtsx" finished: Failure.
I really need to know if the call to the AS400 stored procedure succeeded or not, so I need a way to obtain and evaluate the output parameter. Is there a better way to accomplish what I am trying to do? Any help is appreciated.
Hi All! I have Store Procedure: If exists(Select * From sysobjects Where Name like 'Forum_Topic_SelectFromForum') Drop Procedure Forum_Topic_SelectFromForumgoCREATE PROCEDURE Forum_Topic_SelectFromForum( @ForumID varchar(10)) AS BEGIN TRANSACTIONSELECT * from Forum_Topic where ForumID=@ForumID Order by Tmp DESCIF @@ERROR <> 0 ROLLBACK TRANSACTIONELSE COMMIT TRANSACTION Now, I want to Add 2 Variables: @Offset int, @Count int . With @Offset: the point of data, @Count: sum of row will get. when get data I want it get from @Offset to Added @Count. Help me to rewrite this store procedure. Thanks
I've got some procedure which pages select query, the example is below:
Code Snippet CREATEEND PROC GetCustomersByPage
@PageSize int, @PageNumber int
AS
Declare @RowStart int Declare @RowEnd int
if @PageNumber > 0 Begin
SET @PageNumber = @PageNumber -1
SET @RowStart = @PageSize * @PageNumber + 1; SET @RowEnd = @RowStart + @PageSize - 1 ;
With Cust AS ( SELECT CustomerID, CompanyName, CompanyAddress, ROW_NUMBER() OVER (order by CompanyName) as RowNumber FROM Customers )
select * from Cust Where RowNumber >= @RowStart and RowNumber <= @RowEnd end
How can I change this procedure in order to page the query OVER the column set as an argument? In other words I would like to execute proc like: - exec GetCustomersByPage 10, 1, 'CompanyName' which pages by CompanyName(...OVER (order by CompanyName)...) - exec GetCustomersByPage 10, 1, 'CompanyAddress' which pages by ComanyAddress
1.Sql query (String) 2.Starting index (Integer) 3.Page size (Integer) 4.total records out (Integer)
It works fine for the simple queries like "select * from tblcountry" but give error in case when we have sort of inline query or order clause or some complex query etc.
Despite of what is happing in the procedure can any help me out with a simple store procedure to which i give any query , start index and page size it should give me record set according to the given page.
For example query could be 'Select * from tblcountry where countryid in (select * from tblteachers) order by countryname desc', start index=0 , page size is 100 and total records are 500.
Note: When i pass this query to sql server directly using command object its exectued successfully (this mean that it will also run fine in query analyzer), but i want to use paging in sql server so that is why i need a procedure to implement paging and query could be any its fully dynamic but i will be a valid query.
Hello,I need to have a stored procedure, which performs sorting. Something likethis:CREATE PROCEDURE procname@sortby varchar(30)ASBEGINSELECT some, columnsFROM some_tableORDER BY @sortbyEND(of course, i know this won't work, but it gives the idea of what i mean)Is there a possibility to write a procedure which behaves like that? It isimportant for me not to have multiple procedures just for different sortingcriteria...Thanks,Mike
Hi, i'm trying to enable custom paging and sorting in my grid view control. The trouble i'm getting is the sorting. I have paging working fine with the following code: WITH NewsEntries AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY fldTitle ASC) AS RowNum FROM qryNews ) SELECT * FROM NewsEntries WHERE RowNum BETWEEN @StartRowIndex + 1 AND @StartRowIndex + @MaximumRows I tried replacing fldTitle ASC with @SortBy and passing that it but when i execute the query to test it doesn't do any sorting. After reading an article on a website i now realize i have to put: DECLARE @Sql nvarchar(4000) SET @Sql = 'SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY ' + @SortBy + ') AS RowNum FROM qryNews WHERE fldTitle LIKE ''%' + @SearchBy + '%'' ) AS NewsEntries WHERE RowNum BETWEEN ' + CONVERT(nvarchar(10), @StartRowIndex) + ' + 1 AND ' + CONVERT(nvarchar(10), @StartRowIndex) + ' + ' + CONVERT(nvarchar(10), @MaximumRows) -- Execute the SQL query EXEC sp_executesql @Sql and it works fine when i execute it sql server management studio but when i run my page with the grid view on i get the following error: Incorrect syntax near ')'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ')'.Source Error:
Line 4920: End If Line 4921: Dim dataTable As KIT.tbdNewsDataTable = New KIT.tbdNewsDataTable Line 4922: Me.Adapter.Fill(dataTable) Line 4923: Return dataTable Line 4924: End FunctionSource File: C:WINDOWSMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET Files ootec31cfa3e7f364f7App_Code.jtrijhok.1.vb Line: 4922 Stack Trace:
I have created a stored procedure in sql server 2005 which will fetch a particular record based on the value we supply for a column. It is working fine. The same task i need to implement in my web form. I have a textbox in my webform where i will enter the empage which is in the table. Based on the value the record(s) should get displayed in the gridview. How to acheive this. Pls help me with full coding. it is urgent. Thanx is advance
I used Datagrid to show "Title", "Location" and "Date", It works very well. I want to sort DataGrid data, that is when user click the "Title", "Location" or "Date", my asp.net code will through class and send "Sort" parameter to stores procedure to get the new data and bind to DataGrid.
Here is my stores procedure:
CREATE Procedure JobSearch ( @Search varchar(150), @Sort varchar(50) ) AS