CREATE OR ALTER PROCEDURE sp_DepartmanKayitGoster
AS
BEGIN
	declare @Sorgu nvarchar(max);
	declare @tablename nvarchar(50)
	declare csr_dep cursor for 	
		SELECT t.name
		  FROM sys.tables t,
			   sys.columns c
		 WHERE t.object_id = c.object_id
		   AND c.name = 'Departman';
	SET @Sorgu = '';
	open csr_dep
	fetch next from csr_dep into @tablename
	while @@FETCH_STATUS = 0
	begin			
		IF @Sorgu = ''
			SET @Sorgu = ' Select '''+@tablename+''' as TabloAdi,Departman,count(*) KayitSayisi from ' + @tablename + ' GROUP BY Departman';
		ELSE
			SET @Sorgu = @Sorgu + ' UNION ALL Select '''+@tablename+''' as TabloAdi,Departman,count(*) KayitSayisi from ' + @tablename + ' GROUP BY Departman';	
			
	fetch next from csr_dep into @tablename
	end
	close csr_dep
	deallocate csr_dep
	EXEC sp_executesql @Sorgu;  
END;

--exec sp_DepartmanKayitGoster