选择所有非空SQL Server表的前N行

jpa*_*ich 0 sql sql-server

我正在执行数据库迁移到新的ERP系统,并且当前的Microsoft SQL数据库有超过3000个表,其中95%没有数据导致在找出模式时引起很多悲伤/噪音.

有没有办法可以为数据库中非空的每个表打印标题和前三行数据?

谢谢您的帮助!

Gor*_*off 5

SQL Server不受支持sp_MSforeachtable.所以,你可以这样做:

exec sp_MSforeachtable @command1='select top (3) * from ? where exists (select 1 from ?)';
Run Code Online (Sandbox Code Playgroud)

否则,您将使用游标或其他循环机制来实现基本相同的事情.

编辑:

Jeroen提出了一个非常好的建议:

exec sp_MSforeachtable @command1='if exists (select 1 from ?) select top (3) ''?'' as table_name, t.* from ? t';
Run Code Online (Sandbox Code Playgroud)

这也为额外的spice添加了表名.

  • 这将给出一堆空结果集.考虑`if exists(...)select ...`.(它仍然会缺少表名,所以来自另一个答案的'print`可能也是一个好主意.) (3认同)