选择数据库中每个表的前3行 [英] Select the first 3 rows of each table in a database

查看:270
本文介绍了选择数据库中每个表的前3行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含69个表的数据库,我只想选择每个表的前三个记录.

I have a database with 69 tables and I want to select only the first three records of each table.

我可以每个表执行以下操作:

SELECT TOP 3 * 
  FROM table_schema.table_name

但是,如果我要手动执行此操作,则将花费大量时间.

However if I was to do this manually, it would take a lot of time.

您能建议一个解决方法吗?

Could you please suggest a workaround?

我尝试了此解决方案但我可以使它正常工作(我不知道如何针对MSSQL对其进行修改)

I tried this solution but I can get it to work (I don't know how to modify it for MSSQL)

编辑:感谢您的答复.我可能还不够清楚:我的意思是我想解析每个单独的表,只获得前3个记录,而不是转到下一个表. 以下是我需要的Yaroslav的代码

EDIT Thanks for your replies. I probably wasn't clear enough: I meant I wanted to parse each individual table and only get the top 3 records than move on to the next one. Yaroslav's code below is what I needed

DECLARE @sql VARCHAR(MAX)='';
SELECT @sql=@sql+'SELECT TOP 3 * FROM '+'['+SCHEMA_NAME(schema_id)+'].['+name+']'+';'
  FROM sys.tables
EXEC(@sql)

推荐答案

您在这里:

DECLARE @sql VARCHAR(MAX)='';
SELECT @sql=@sql+'SELECT TOP 3 * FROM '+'['+SCHEMA_NAME(schema_id)+'].['+name+']'+';'
  FROM sys.tables
EXEC(@sql)

这篇关于选择数据库中每个表的前3行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆