In an anonymous code block, a DO loop, it's not possible to open a cursor. This is only possible through functions or procedures. However, a FOR loop within an anonymous code block will use a cursor internally, so you could rewrite the query that way.