-- 创建存储过程
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 删除现有的存储过程(如果存在)
DROP PROCEDURE IF EXISTS [dbo].[GetTopN]
GO
-- 创建新的存储过程
CREATE PROCEDURE [dbo].[GetTopN]
@DatabaseName NVARCHAR(255),
@TopN INT
AS
BEGIN
DECLARE @TableName NVARCHAR(255)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @DynamicSQL NVARCHAR(MAX)
-- 临时表存储所有表名
CREATE TABLE #TableList (TableName NVARCHAR(255))
-- 动态构建查询获取所有表名并插入到临时表
SET @SQL = '
INSERT INTO #TableList (TableName)
SELECT TABLE_NAME
FROM ' + QUOTENAME(@DatabaseName) + '.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = ''BASE TABLE''
'
EXEC sp_executesql @SQL
-- 初始化动态SQL
SET @DynamicSQL = ''
-- 表的游标
DECLARE table_cursor CURSOR FOR
SELECT TableName FROM #TableList
-- 打开游标
OPEN table_cursor
-- 循环每个表
FETCH NEXT FROM table_cursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
-- 构建查询,检查表是否有数据
SET @SQL = 'IF EXISTS (SELECT 1 FROM ' + QUOTENAME(@DatabaseName) + '.[dbo].' + QUOTENAME(@TableName) + ') ' +
'BEGIN ' +
'SELECT TOP ' + CAST(@TopN AS NVARCHAR) + ' * FROM ' + QUOTENAME(@DatabaseName) + '.[dbo].' + QUOTENAME(@TableName) + '; ' +
'END'
-- 将SQL语句添加到动态SQL中
SET @DynamicSQL = @DynamicSQL + @SQL + CHAR(13) + CHAR(10)
-- 获取下一个表
FETCH NEXT FROM table_cursor INTO @TableName
END
-- 关闭和释放游标
CLOSE table_cursor
DEALLOCATE table_cursor
-- 删除临时表
DROP TABLE #TableList
-- 打印生成的动态SQL以供调试(可选)
-- PRINT @DynamicSQL
-- 执行生成的所有查询
EXEC sp_executesql @DynamicSQL
END
GO