GO
/****** Object:  StoredProcedure [dbo].[sp_GetTermek]    Script Date: 2016.02.19. 10:53:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Hoffmann Zsolt
-- Create date: 2016-02-19
-- Description:	Termek lekérdezés
-- =============================================
CREATE PROCEDURE [dbo].[sp_GetTermek]
	@FoglalkozasId int,
	@OsztCsopId int
AS
BEGIN

	SET NOCOUNT ON;

	
	with q (ID,Nev,Tipus) as
	( select 
	T_TEREM.ID,
	T_TEREM.C_NEV Nev,
	'1' Tipus
	from T_TEREM
	left join T_TEREM_FOGLALKOZAS on T_TEREM_FOGLALKOZAS.C_TEREMID = T_TEREM.ID
	left join T_FOGLALKOZAS on T_FOGLALKOZAS.ID = T_TEREM_FOGLALKOZAS.C_FOGLALKOZASID
	where T_TEREM.TOROLT = 'F' and
	T_FOGLALKOZAS.TOROLT = 'F' and
	T_FOGLALKOZAS.ID = @FoglalkozasId except
	(
	select
	T_TEREM.ID,
	T_TEREM.C_NEV Nev,
	'1' Tipus
	from T_TEREM
	inner join 
	(select C_TEREMID from T_OSZTALYCSOPORT where TOROLT = 'F' and ID = @OsztCsopId) ocs on ocs.C_TEREMID = T_TEREM.ID
	where T_TEREM.TOROLT = 'F') 
	union all select
	T_TEREM.ID,
	T_TEREM.C_NEV Nev,
	'2' Tipus
	from T_TEREM
	inner join 
	(select C_TEREMID from T_OSZTALYCSOPORT where TOROLT = 'F' and ID = @OsztCsopId) ocs on ocs.C_TEREMID = T_TEREM.ID
	where T_TEREM.TOROLT = 'F')
	select ID,Nev,Tipus from q
	union
	select
	T_TEREM.ID,
	T_TEREM.C_NEV Nev,
	'3' Tipus
	from T_TEREM
	where T_TEREM.TOROLT = 'F'
	and T_TEREM.ID not in (select ID from q)

END
