Insert where not already available for FK?
You can just insert into table where fk not in the criteria you specified. This all can be a single insert statement. No need to do RBAR.

It sounds like you're looking to insert where you have fk records that do not have a corresponding "log" record, then insert.

insert into table
select distinct name, fk
from table t
where fk not in (
  select distinct fk
  from table t1
  where name like 'log%'
    and t1.fk is not null)


This is really crude but... just want to make sure I understood you correctly.

Also, in the future, if you do need to do a RBAR operation...

while ((select count(1) from @nolog_ids) &gt; 0)
begin
    declare @currentid int
    set @currentid = (select top 1 ids from @nolog_ids)

    insert into table (name, fk)
    select 1, 'log', @currentid

    delete from @nolog_ids where ids = @currentid
end


I prefer to use this instead... more readable and potentially faster.

declare @currentid int

while exists (select * from @nolog_ids)
begin

    select top 1 @currentid = ids from @nolog_ids

    insert into table (name, fk)
    select 1, 'log', @currentid

    delete from @nolog_ids where ids = @currentid

end