CREATE OR ALTER FUNCTION MIG_GET_PREFERENCE_VALUE_Fn
(
    @InputApp NVARCHAR(MAX)
   ,@TargetPropName NVARCHAR(MAX) 
   ,@LegacyPropName NVARCHAR(MAX) 
   ,@LegacyPropGuiType NVARCHAR(MAX)  
   ,@TargetDataType NVARCHAR(MAX) 
   ,@TargetDomain NVARCHAR(MAX) 
   ,@DefaultValue NVARCHAR(MAX) 
   ,@PropValue NVARCHAR(MAX) 
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
	DECLARE @result NVARCHAR(MAX)
	SET @result = NULL

	IF @TargetDomain = 'pdyesno'
		BEGIN
			IF @PropValue = '1'  
				SET @result = '1'
			ELSE 
				SET @result = '2'
		END
	ELSE IF @TargetDataType = 'E'
		BEGIN
			SELECT 
				@result = TargetPropValue
			FROM MIG_PROPS_LIST_VALUES_MAPPING 
			WHERE AppName = @InputApp 
			 AND LegacyPropName = @LegacyPropName 
			 AND SourcePropValue = @PropValue

			IF @result IS NULL 
				SELECT 
					@result = TargetPropValue
				FROM MIG_PROPS_LIST_VALUES_MAPPING 
				WHERE AppName = '*' 
				 AND LegacyPropName = @LegacyPropName 
				 AND SourcePropValue = @PropValue

			IF @result IS NULL
				SET @result = @DefaultValue
		END
	ELSE IF ISNULL(@PropValue, '') = ''
		SET @result = @DefaultValue
	ELSE
		SET @result = @PropValue

	RETURN @result
END



