I am trying to create an script and I need to iterate the rows of a table, but I want to order by type and later by ID. I am using this code:
declare @MyTempTable table
(
MyId bigint
);
INSERT INTO @MyTempTable
(MyId)
SELECT MyId
FROM MyTable
where MyForeignKey = 8
order by MyIdType, MyId;
while exists(select 1 from @MyTempTable)
begin
select top 1 @myFirstRow = x.MyId from @MyTempTable x;
--Do something
end
The problem is that when I get the first row of the temp table, I don't get the expected row, I get the row with the lowest ID, but it is of a type with higher type, so it seems that when I populate the temp table the order condition is not took in account.
So I would like to know how I could iterate the result in the order that I need, first order by type to group the rows by type and later order by ID in each group.