I’ve a beginner question.
This is a piece of code that works:
declare @RowNr int = 1
declare @CA int = 0
While @RowNr <= 1000
BEGIN
With CCWithRow AS
(
SELECT CA ,ROW_NUMBER() OVER (order by CA) as RowNr
FROM myCATable
)
SELECT @CA = CA, @RowNr = RowNr
FROM CCWithRow
WHERE RowNr = @RowNr
Set @RowNr += 1
--Doing something with @CA here
END
This code doesn’t:
declare @RowNr int = 1
declare @CA int = 0
With CCWithRow AS
(
SELECT CA ,ROW_NUMBER() OVER (order by CA) as RowNr
FROM myCATable
)
While @RowNr <= 1000
BEGIN
SELECT @CA = CA, @RowNr = RowNr
FROM CCWithRow
WHERE RowNr = @RowNr
Set @RowNr += 1
--Doing something with @CA here
END
Question: Why do I have to “define” the WITH inside the loop?
I know that there are better ways to solve the original problem, so that shouldn’t be the subject. Just want to know, why I can’t define WITH outside of the loop and use it inside.
From BOL
So the common table expression usage must always occur immediately after the end of the CTE definition as it is not in scope to reference anywhere else. This case is no exception.