November 25, 2013 at 10:26 am
I want to get the total number of records for with Table before using it in a variable .. So any Ideas for how can I handle that
DECLARE @totalCount int
;WITH tmpTable AS (SELECT DISTINCT * ,ROW_NUMBER() OVER ( ORDER BY InventorySys ) AS RowNumber FROM dbo.Inventory)
SELECT @totalCount = Count(*) FROM tmpTable
SELECT * , @totalCount as RecordsCount
FROM tmpTable
WHERE (RowNumber BETWEEN @StartIndex AND @EndIndex) OR @StartIndex = 0 OR @EndIndex = 0
ORDER BY RowNumber
but I get this error Invalid object name 'tmpTable'.
I can handle it using SubQuery but i don't like that way a lot "SubQuery"
;WITH tmpTable AS (SELECT DISTINCT * ,ROW_NUMBER() OVER ( ORDER BY InventorySys ) AS RowNumber FROM dbo.Inventory)
SELECT * , (SELECT Count(*) FROM tmpTable) as RecordsCount
FROM tmpTable
WHERE (RowNumber BETWEEN @StartIndex AND @EndIndex) OR @StartIndex = 0 OR @EndIndex = 0
ORDER BY RowNumber
So any Ideas for how can I handle that without using subquery Solution ???
November 25, 2013 at 10:31 am
It's basically the same as using the subquery but using another CTE.
WITH tmpTable AS (
SELECT DISTINCT *,
ROW_NUMBER() OVER ( ORDER BY InventorySys ) AS RowNumber
FROM dbo.Inventory
),
Total AS(
SELECT totalCount = Count(*)
FROM tmpTable
)
SELECT tmp.* , tot.totalCount as RecordsCount
FROM tmpTable tmp
CROSS JOIN Total tot
WHERE (tmp.RowNumber BETWEEN 1 AND 6) OR 1 = 0 OR 6 = 0
ORDER BY tmp.RowNumber
November 25, 2013 at 10:33 am
I just noticed the additional conditions on your WHERE clause that will always evaluate to false
OR 1 = 0 OR 6 = 0
Why do you even have them? What were you trying to accomplish?
November 25, 2013 at 5:37 pm
And then there's this:
SELECT DISTINCT * ,ROW_NUMBER() OVER ( ORDER BY InventorySys )
The DISTINCT has no meaning here (just drags down the performance) because the ROW_NUMBER() will ensure that each record is distinct.
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St
November 26, 2013 at 3:22 am
Yes ..sorry for that ..It shall be startIndex and EndIndex Paramaters
November 26, 2013 at 3:27 am
OK ..Thanks a lot "dwain.c" .. Yes your are right ..but that was just try to simplify my real script .. The Real Script has another columns order by ..But thanks a lot for your note 🙂
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply