HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

How to select the first 10 records for each table in the same database using sql

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
sametheeachsqlrecordsdatabasefirstforusinghow

Problem

I have 50+ tables in a database.

I don't want to use the following SQL on each table in a database.

select * from {table_name}


So, is it possible to display the first 10 records for each table inside the same database using sql?

Solution

I'd be careful about using sp_MSforeachtable, as it uses the same code pattern as sp_MSforeachdb. I've pointed out the problems with sp_MSforeachdb here (work backward) and was told it wouldn't be fixed on Connect (before they killed it, and so this link no longer works) here.

Instead I would do something like this (which also includes the table name in the output, probably useful):

DECLARE @sql nvarchar(max) = N'';

SELECT @sql += N'

SELECT TOP (10) [table] = N''' + REPLACE(name, '''','') + ''', * 
    FROM ' + QUOTENAME(SCHEMA_NAME([schema_id]))
  + '.' + QUOTENAME(name) + ';'
FROM sys.tables AS t;

PRINT @sql;
-- EXEC sys.sp_executesql @sql;


When you're satisfied with the PRINT output (note that it will truncate at 8K), uncomment the EXEC.

Code Snippets

DECLARE @sql nvarchar(max) = N'';

SELECT @sql += N'

SELECT TOP (10) [table] = N''' + REPLACE(name, '''','') + ''', * 
    FROM ' + QUOTENAME(SCHEMA_NAME([schema_id]))
  + '.' + QUOTENAME(name) + ';'
FROM sys.tables AS t;

PRINT @sql;
-- EXEC sys.sp_executesql @sql;

Context

StackExchange Database Administrators Q#35529, answer score: 11

Revisions (0)

No revisions yet.