Question

I am facing a very isolated problem regarding to the dynamic sql query. I have two queries running on a single stored procedure. They are following

First query:

SELECT *
                FROM (
                      SELECT  ROW_NUMBER() OVER(ORDER BY viwPerformance.LastModifiedOn DESC) AS rowNumber,viwPerformance.* FROM viwPerformance WHERE OrgId=218 AND EmployeeId = 1668 AND IsTerminate = 0 AND TagId LIKE '%' + CAST(2893 AS VARCHAR) + '%' AND Archive='False' AND SmartGoalId IS NOT NULL
                     ) AS E
                WHERE  rowNumber >= 1 AND
                       rowNumber <  11

it results all the column values and the SmartGoalId as

4471,2815,4751,4733,4863,4690,4691,4692,4693,4694

And the second query (here I need only SmartgoalId from the above query so I use stuff)

SELECT @strGoalIds = STUFF((SELECT ',' + CAST(SmartGoalId AS VARCHAR)
                FROM (
                      SELECT  ROW_NUMBER() OVER(ORDER BY viwPerformance.LastModifiedOn DESC) AS rowNumber,viwPerformance.* FROM viwPerformance WHERE OrgId=218 AND EmployeeId = 1668 AND IsTerminate = 0 AND TagId LIKE '%' + CAST(2893 AS VARCHAR) + '%' AND Archive='False' AND SmartGoalId IS NOT NULL
                     ) AS E
                 WHERE  rowNumber >= 1 AND
                       rowNumber <  11 FOR XML PATH('')), 1, 1, '')

and it's results the SmartgoalId as

4471,2815,4751,4733,4863,4651,4690,4691,4692,4693

Please note that the last id "4694" is not available from above query as the "4651"is added to it but it's not available from first query and this is correct that "4651" should not be in the second query result.

So my main point is why the second query gives different results as it's the same as the first query.

Note: Am I right that the Stuff function reversing the values and not giving them in correct order.

Was it helpful?

Solution

Because you have some rows with the same value for LastModifiedOn it depends how you want to handle ties.

If you want this query to always return the 10 most "recent" rows but always return the same ones when there are ties you can add another column to your ORDER BY viwPerformance.LastModifiedOn DESC clause that will make the sort unique and unchanging, like:

ORDER BY viwPerformance.LastModifiedOn,viwPerformance.SmartGoalId DESC)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top