需要在所有数据库的所有表中获得前10行

时间:2015-05-27 16:18:55

标签: sql sql-server tsql

EXEC sp_MSforeachdb
@command1 = 'select db_name
EXEC [?].dbo.sp_MSforeachtable 
@command2 = ''SELECT TOP 10 * from &''
@replacechar=''&''
'

以上查询在所有数据库的所有表中给出了前10行,但我无法在结果中获取表名和数据库名。请帮忙。

谢谢

2 个答案:

答案 0 :(得分:2)

您可以在select语句中添加db_name()和表名:

  EXEC sp_MSforeachdb
   @command1 = 'select name from sys.databases where name <>''tempdb'' EXEC [?].dbo.sp_MSforeachtable @command1 = ''SELECT TOP 10 db_name() AS DB_Name, ''''&'''' AS Table_name , * from &'', @replacechar=''&'' '

答案 1 :(得分:1)

EXEC sp_MSforeachdb
@command1 = '
IF not exists(select 1 where ''?'' in  (''master'',''model'',''msdb'',''tempdb''))


EXEC [?].dbo.sp_MSforeachtable
 @command1 = ''SELECT TOP 10 db_name() AS DB_Name, ''''&'''' AS  Table_name , * from &'', @replacechar=''&'' '