选择数据库中每个表的前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)