CREATE FUNCTION CF_Preset_Valor (@Id_Usuario SMALLINT, @Id_Ventana VARCHAR(100) ,@Nombre VARCHAR(100), @Modo CHAR(1) )
RETURNS VARCHAR(8000)
AS
BEGIN

DECLARE @Retorno VARCHAR(8000)

IF ISNULL(@Id_Usuario,0) != 0
BEGIN 
	IF @Modo IN ('A','T')
	BEGIN
		SET @Retorno = (SELECT Valor 
						FROM xVentanas_Items_Users
						WHERE Id_Ventana = @Id_Ventana
						AND Nombre = @Nombre
						AND Id_Usuario = @Id_Usuario
						AND ISNULL(Flag_Modif,0) = 1
						AND (ISNULL(Flag_Todas,0) = 1 
							OR ISNULL(Flag_Agregar,0) = 1))
		IF @Retorno IS NOT NULL
			RETURN @Retorno
	END

	IF @Modo IN ('C','T')
	BEGIN
		SET @Retorno = (SELECT Valor 
						FROM xVentanas_Items_Users
						WHERE Id_Ventana = @Id_Ventana
						AND Nombre = @Nombre
						AND Id_Usuario = @Id_Usuario
						AND ISNULL(Flag_Modif,0) = 1
						AND (ISNULL(Flag_Todas,0) = 1 
							OR ISNULL(Flag_Cambiar,0) = 1))

		IF @Retorno IS NOT NULL
			RETURN @Retorno
	END

	IF @Modo IN ('B','T')
	BEGIN
		SET @Retorno = (SELECT Valor 
						FROM xVentanas_Items_Users
						WHERE Id_Ventana = @Id_Ventana
						AND Nombre = @Nombre
						AND Id_Usuario = @Id_Usuario
						AND ISNULL(Flag_Modif,0) = 1
						AND (ISNULL(Flag_Todas,0) = 1 
							OR ISNULL(Flag_Borrar,0) = 1))

		IF @Retorno IS NOT NULL
			RETURN @Retorno
	END
END

IF @Modo IN ('A','T')
BEGIN
	SET @Retorno = (SELECT Valor 
					FROM xVentanas_Items
					WHERE Id_Ventana = @Id_Ventana
					AND Nombre = @Nombre
					AND ISNULL(Flag_Modif,0) = 1
					AND (ISNULL(Flag_Todas,0) = 1 
						OR ISNULL(Flag_Agregar,0) = 1))

END

IF @Modo IN ('C','T')
BEGIN
	SET @Retorno = (SELECT Valor 
					FROM xVentanas_Items
					WHERE Id_Ventana = @Id_Ventana
					AND Nombre = @Nombre
					AND ISNULL(Flag_Modif,0) = 1
					AND (ISNULL(Flag_Todas,0) = 1 
						OR ISNULL(Flag_Cambiar,0) = 1))

END

IF @Modo IN ('B','T')
BEGIN
	SET @Retorno = (SELECT Valor 
					FROM xVentanas_Items
					WHERE Id_Ventana = @Id_Ventana
					AND Nombre = @Nombre
					AND ISNULL(Flag_Modif,0) = 1
					AND (ISNULL(Flag_Todas,0) = 1 
						OR ISNULL(Flag_Borrar,0) = 1))

END



RETURN @Retorno

END