CREATE FUNCTION [dbo].[fn_GetSurfaceCalculationDivide]
( 
	@surfaceItemId INT
	,@actionSource INT
	,@actionValue VARCHAR(250)
)
RETURNS DECIMAL(18,2)
AS
BEGIN
DECLARE @returnVal DECIMAL(18,2)

SELECT @returnVal =	
CASE WHEN (SELECT	CAST(CASE F.surfaceFieldTypeId
						WHEN 4 THEN D.surfaceFieldValueNum
						WHEN 5 THEN D.surfaceFieldValueDecimal
						END
					AS DECIMAL(18,2))
			FROM	dbo.pal_SurfaceField F
					JOIN dbo.pal_SurfaceFieldData D 
						ON D.surfaceFieldID = F.recId
			WHERE	D.surfaceFieldID = @actionValue
					AND D.surfaceItemId = @surfaceItemId)
			= 0 
	THEN 0 
	ELSE
		CAST(
		(SELECT	CAST(CASE F.surfaceFieldTypeId
					WHEN 4 THEN D.surfaceFieldValueNum
					WHEN 5 THEN D.surfaceFieldValueDecimal
					END
				AS DECIMAL(18,2))
		FROM	dbo.pal_SurfaceField F
				JOIN dbo.pal_SurfaceFieldData D 
					ON D.surfaceFieldID = F.recId
		WHERE	D.surfaceFieldID = @actionSource
				AND D.surfaceItemId = @surfaceItemId)
		/
		(SELECT	CAST(CASE F.surfaceFieldTypeId
					WHEN 4 THEN D.surfaceFieldValueNum
					WHEN 5 THEN D.surfaceFieldValueDecimal
					END
				AS DECIMAL(18,2))
		FROM	dbo.pal_SurfaceField F
				JOIN dbo.pal_SurfaceFieldData D 
					ON D.surfaceFieldID = F.recId
		WHERE	D.surfaceFieldID = @actionValue
				AND D.surfaceItemId = @surfaceItemId)
		AS DECIMAL(18,2))
	END
RETURN	@returnVal

END
GO

