GO
CREATE FUNCTION TopStud(@numk int)
RETURNS varchar(max)
BEGIN
DECLARE @c int, @stud varchar(max), @tb_name varchar(max), @tb_sql varchar(max);
SET @c = (SELECT COUNT(name) FROM tempdb.sys.tables WHERE name LIKE '##tb_'+ '[0-9]'+ '[0-9]'+ '[0-9]'+'_'+ CAST((@numk * 2 - 1) as varchar)
OR name LIKE '##tb_'+ '[0-9]'+ '[0-9]'+ '[0-9]'+'_'+ CAST((@numk * 2) as varchar));
WHILE @c > 0
BEGIN
SET @tb_name = (SELECT name FROM (SELECT name,ROW_NUMBER() over (order by name) as rnum FROM tempdb.sys.tables WHERE name LIKE '##tb_'+ '[0-9]'+ '[0-9]'+ '[0-9]'+'_'+ CAST((@numk * 2 - 1) as varchar)
OR name LIKE '##tb_'+ '[0-9]'+ '[0-9]'+ '[0-9]'+'_'+ CAST((@numk * 2) as varchar)) as t1 WHERE rnum = @c);
SET @tb_sql = 'SELECT DISTINCT TOP(5) CONCAT(Id, FIO, CAST(SUM(Mark)/COUNT(Mark) as varchar)) FROM Students
JOIN Discipline ON DGroupNum = GroupNum
JOIN '+ @tb_name+' ON Id = IdStud WHERE DSemestr = '+CAST((@numk * 2 - 1) as varchar)+' OR DSemestr = '+CAST((@numk * 2) as varchar)+' GROUP BY Id, FIO;'
EXEC(@tb_sql);
SET @c = @c - 1;
END;
RETURN @stud;
END;