Sql-server – How to select 1st row of each table and insert that data to a new table

sql server

i have 5 tables (tab1, tab2, tab3, tab4 and tab5) and all the 5 tables has same table
definition. I want to select 1st row of each table and insert those 5 rows in
new table(newtab). I was only able to write query that select 1 row from one table and
insert that into newtab. How can i select 1st 5 rows from all the table and insert them
into newtab in one query.

In this case i have to deal with only 5 tables so its easy using union but when i want to select 1st rows from 100 tables then the query will become but lengthy using UNION.

Best Answer

This is not a complete answer (I'm sorry), but maybe a starting point for further thinking.

For a low number of tables UNION is the best approach IMHO. In special if the list of tables are not changing.

For a bigger number of tables you might can think of using some T-SQL and iterate through a list of tables and building up your query with dynamic SQL -- with this you can select your line(s) into a temporary table maybe.

As I'm not sure where you will get your list of tables from, you could get it from some cursor out of system tables or from some hard coded list maybe.