I am trying to use row_number or rank just to insert a row number so I can enumerate over a temp table without using a cursor. Both functions give me error “Incorrect syntax near ‘rank’, expected ‘OVER'”. I do not need all of the functionality + performance impact that OVER provides – I don’t care one bit about order/ranking etc. I’m sure I’ve done this before but it was a few years ago, can someone point me to the correct function?
declare @SomeTempTable table (RowNum int NOT NULL, SomeField int NOT NULL);
insert into @SomeTempTable
select rank() as RowNum, SomeField
from SomeTable
declare @RowNum int = 1;
declare @NumRows int = (select max(RowNum) from @SomeTempTable);
while@RowNum <= @NumRows
begin
declare @SomeField int;
select @SomeField = SomeField
from @SomeTempTable
where RowNum = @RowNum;
--TODO: Do stuff
set @RowNum = @RowNum + 1;
END
Hmmm, you don’t get to decide on the syntax of SQL functions, even if it is appealing to you.
There are two methods to get what you want. The first is the standard method, that doesn’t use windows functions at all:
Voila! Let the identity do the work.
The second is the approach you were taking:
The “order by (Select NULL)” appears to be a magical incantation in SQL Server to just assign numbers, without actually doing a sort.
As an aside, when you do an insert, you should always specify the columns in the insert statement.
Also, it is quite possible that the WHILE loop could be re-written as a query, making everything more efficient (not always, but sometimes).