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

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.


Use sp_MSforeachtable

EXEC sp_MSforeachtable 'select top(10) * from ?'

To show the table Name you should change it like this :

EXEC sp_MSforeachtable 'select "?" as table_Name , * from ?'

sp_MSforeachtable is great. but if you want to somehow limit which tables to look at (for example, just 'dbo' schema) you can generate select scripts like this:

select 'Select Top 10 * From ' + SCHEMA_NAME(schema_id) + '.' + name 
from sys.objects 
where type = 'U' -- and SCHEMA_NAME(schema_id)  = 'dbo'