title: Export the top 5 rows of every table in a database to excel - MS SQL Server
body: <p>I would like a way to export the top 5 rows of every table within a database from SQL to an excel spreadsheet. The desired output would be an excel spreadsheet where each tab would be a different table from the database, containing the top 5 records (also a way of identifying what tab contains what table).</p>
  
  <p>In the past I have done this for smaller databases (but I am trying to cut out the manual process, as I need to do this on several large databases), using the following methods:</p>
  
  <pre><code>USE Database_Name
  GO 
  SELECT *
  FROM sys.Tables
  GO
  </code></pre>
  
  <p>I use this query to get a list of the table names within the database, then run the following code to get the top 5 rows of those tables in the same database:</p>
  
  <pre><code>DECLARE @sql VARCHAR(MAX)='';
  SELECT @sql=@sql+'SELECT TOP 5 * FROM '+'['+SCHEMA_NAME(schema_id)+'].
  ['+name+']'+';'
  FROM sys.tables
  EXEC(@sql)
  </code></pre>
  
  <p>The first and second query produce the tables in the same order. So previously I had copy and pasted the list of names into excel (from the first query), created a tab for each table name, then copy and pasted the top 5 rows (produced by the second query) into those tabs. I feel as if this could be done in a much better fashion/ be automated. Any help or suggestions would be much appreciated!</p>