﻿

-- =============================================
-- Author:		Dr. Stefan Ott
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[ne]
(
	@value SQL_VARIANT 
	,@alternative SQL_VARIANT
)
RETURNS SQL_VARIANT
AS
BEGIN
	DECLARE @ret SQL_VARIANT;
	
	IF SQL_VARIANT_PROPERTY(@value, 'BaseType') = 'varchar'
		BEGIN
			
			If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 50
				BEGIN 
					DECLARE @v1 varchar(50) = ISNULL(try_cast(@value as varchar(50)), '');
					SET @ret = IIF( @v1 <> '', @v1, try_CAST(@alternative as varchar(50)));
				END
			ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 255
				BEGIN 
					DECLARE @v2 varchar(255) = ISNULL(try_cast(@value as varchar(255)), '');
					SET @ret = IIF( @v2 <> '', @v2, try_CAST(@alternative as varchar(255)));
				END
			ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 1000
				BEGIN 
					DECLARE @v3 varchar(1000) = ISNULL(try_cast(@value as varchar(1000)), '');
					SET @ret = IIF( @v2 <> '', @v2, try_CAST(@alternative as varchar(1000)));
				END
			ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 4000
				BEGIN 
					DECLARE @v4 varchar(4000) = ISNULL(try_cast(@value as varchar(4000)), '');
					SET @ret = IIF( @v4 <> '', @v4, try_CAST(@alternative as varchar(4000)));
				END
			ELSE 
				BEGIN 
					DECLARE @v5 varchar(8000) = ISNULL(try_cast(@value as varchar(8000)), '');
					SET @ret = IIF( @v5 <> '', @v4, try_CAST(@alternative as varchar(8000)));
				END


		END
	ELSE IF SQL_VARIANT_PROPERTY(@value, 'BaseType') = 'nvarchar'
		BEGIN
			
			If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 50
				BEGIN 
					DECLARE @nv1 nvarchar(50) = ISNULL(try_cast(@value as nvarchar(50)), '');
					SET @ret = IIF(@nv1 <> '', @nv1, try_CAST(@alternative as nvarchar(50)));
				END
			ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 255
				BEGIN 
					DECLARE @nv2 nvarchar(255) = ISNULL(try_cast(@value as nvarchar(255)), '');
					SET @ret = IIF(@nv2 <> '',@nv2, try_CAST(@alternative as nvarchar(255)));
				END
			ELSE If SQL_VARIANT_PROPERTY(@value, 'MaxLength') <= 1000
				BEGIN 
					DECLARE @nv3 nvarchar(1000) = ISNULL(try_cast(@value as nvarchar(1000)), '');
					SET @ret = IIF(@nv2 <> '',@nv2, try_CAST(@alternative as nvarchar(1000)));
				END
			ELSE
				BEGIN 
					DECLARE @nv4 nvarchar(4000) = ISNULL(try_cast(@value as nvarchar(4000)), '');
					SET @ret = IIF(@nv4 <> '',@nv4, try_CAST(@alternative as nvarchar(4000)));
				END


		END

	RETURN @ret
END