﻿DROP FUNCTION IF EXISTS [dbo].[fnGetKapcsolodoTantargyak]
GO

CREATE FUNCTION [dbo].[fnGetKapcsolodoTantargyak] (
	 @pIntezmenyId		INT 
	,@pTanevId			INT
	,@pTantargyId		INT
) 
RETURNS @return TABLE (
	 ID					INT
	,C_FOTARGYID		INT
	,C_NEV				NVARCHAR(255)
	,C_TARGYKATEGORIA 	INT
	,C_INTEZMENYID	 	INT
	,C_TANEVID 			INT
)
BEGIN   
	IF @pTantargyId IS NULL
	BEGIN   
		INSERT INTO @return 
		SELECT ID, C_FOTARGYID, C_NEV, C_TARGYKATEGORIA, C_INTEZMENYID, C_TANEVID FROM T_TANTARGY_OSSZES WHERE C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F'
	END
	ELSE   
	BEGIN   
		INSERT INTO @return 
		SELECT ID, C_FOTARGYID, C_NEV, C_TARGYKATEGORIA, C_INTEZMENYID, C_TANEVID FROM T_TANTARGY_OSSZES WHERE ID = @pTantargyId AND C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F'
		UNION
		SELECT ID, C_FOTARGYID, C_NEV, C_TARGYKATEGORIA, C_INTEZMENYID, C_TANEVID FROM T_TANTARGY_OSSZES WHERE C_FOTARGYID = @pTantargyId AND C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F'
		UNION
		SELECT ID, C_FOTARGYID, C_NEV, C_TARGYKATEGORIA, C_INTEZMENYID, C_TANEVID FROM T_TANTARGY_OSSZES WHERE C_FOTARGYID = (SELECT C_FOTARGYID FROM T_TANTARGY_OSSZES WHERE ID = @pTantargyId AND C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F') AND C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F'
		UNION
		SELECT ID, C_FOTARGYID, C_NEV, C_TARGYKATEGORIA, C_INTEZMENYID, C_TANEVID FROM T_TANTARGY_OSSZES WHERE ID = (SELECT C_FOTARGYID FROM T_TANTARGY_OSSZES WHERE ID = @pTantargyId AND C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F') AND C_INTEZMENYID = @pIntezmenyId AND C_TANEVID = @pTanevId AND TOROLT = 'F'
		ORDER BY C_FOTARGYID ASC, C_NEV ASC
	END
	RETURN  
END


GO

