简体   繁体   中英

Is there a way to SELECT the TOP N rows from a table and delete them afterwards?

I'd like to achieve the following within Teradata.

Given a table, I'd like to

  • get the TOP N rows from a table, eg, SELECT TOP 100 * FROM table ORDER BY idx
  • delete those rows afterwards, eg DELETE FROM table WHERE idx IN (SELECT TOP 100 idx FROM table ORDER BY idx)

The second query doesn'T even work (TOP not allowed in subquery).

Would there be a straight forward way to achieve this behaviour? Ideally even in one rush, but I could also use locks.

I also looked into Queue tables, but they only allow TOP 1 , so obviously designed to pop exactly one element at a time.

Top N option is not supported in subquery

It's just not allowed in a subquery , but you can wrap it in a Derived Table :

DELETE FROM table 
WHERE idx IN 
 ( SELECT *
   FROM
    ( SELECT TOP 100 idx FROM table ORDER BY idx
    ) AS dt
 )

A subquery might be Correlated , but not a Derived Table:-)

But, why do you actually need this? Hopefully not in a loop to get smaller transactions.

You can use a temp table. Example:

CREATE MULTISET VOLATILE TABLE tmp_top_100_idx AS
(SELECT TOP 100 * FROM table ORDER BY idx)
WITH DATA
ON COMMIT PRESERVE ROWS

DELETE FROM table 
WHERE idx IN (SELECT idx FROM tmp_top_100_idx)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM