CREATE FUNCTION [C6StagingPeriodico].[Info_DaProdottoCSaCatalogo_asu2]
(
	@TipoProdotto varchar(5),
	@CodInterno varchar(13),
	@CodMAF varchar(13),
	@CodISIN varchar(16),
	@CodSottoprodotto varchar(13)
)
RETURNS varchar(63)
AS
BEGIN
	-- Declare the return variable here
		DECLARE @ResultVar  VARCHAR(63)
	-- Add the T-SQL statements to compute the return value here
	IF @TipoProdotto in ('FI', 'GE', 'ASUL', 'ASVI','ASU1', 'ASCM', 'AC','CC' )    -- TRINGALI inseriti CC
	--OR (@CodSottoprodotto NOT IN ('VAR5','VAR10','VAR15') and @TipoProdotto = 'ASU1')
	SELECT TOP 1 @ResultVar = CATALOGUEID 
	FROM C6StagingPeriodico.CATITEMREF cat
	where 1=1 and cat.COD_INTERNO = (case rtrim(isnull(@CodInterno,'')) when '' then '$' else @CodInterno end) 
	and cat.COD_SOTTOPRODOTTO= (case rtrim(isnull(@CodSottoprodotto,'')) when '' then '$' else @CodSottoprodotto end)
	ORDER BY ISVISIBLE DESC
	IF @TipoProdotto in ('ASU2')    -- TRINGALI inseriti CC --V Inseriti ASU2
	--OR (@CodSottoprodotto IN ('VAR5','VAR10','VAR15') and @TipoProdotto = 'ASU1')
	SELECT TOP 1 @ResultVar = CATALOGUEID 
	FROM C6Staging.CATITEMREF cat
	where 1=1 and cat.COD_INTERNO = (case rtrim(isnull(@CodInterno,'')) when '' then '$' else @CodInterno end) 
	and cat.COD_SOTTOPRODOTTO= (case rtrim(isnull(@CodSottoprodotto,'')) when '' then '$' else @CodSottoprodotto end)
	and cat.cod_isin = @CodISIN
	ORDER BY ISVISIBLE DESC
	IF @TipoProdotto in ('DT','ASD' ) 
	SELECT TOP 1 @ResultVar = CATALOGUEID 
	FROM C6StagingPeriodico.CATITEMREF cat
	where 1=1 and cat.COD_INTERNO = (case rtrim(isnull(@CodInterno,'')) when '' then '$' else @CodInterno end)
	ORDER BY ISVISIBLE DESC
	IF @TipoProdotto in ('GES' ) 
	SELECT TOP 1 @ResultVar = CATALOGUEID 
	FROM C6StagingPeriodico.CATITEMREF cat
	where 1=1 
	and cat.COD_INTERNO = (case rtrim(isnull(@CodInterno,'')) when '' then '$' else @CodInterno end) 
	and cat.COD_MAF=(case rtrim(isnull(@CodMAF,'')) when '' then '$' else @CodMAF end)
	ORDER BY ISVISIBLE DESC
	-- Return the result of the function
	RETURN @ResultVar
END