CREATE FUNCTION [dbo].[GeneraChiaveContratto]
(
@TipoProdotto varchar(5)='',
@CodInterno varchar(13)='', @CodMAF varchar(13)='', @CodISIN varchar(16)='', @CodSottoprodotto varchar(13)='',
@CodiceContratto varchar(11)='',@NumeroPolizza  varchar(11)= '', @Conto  varchar(12)= '',
@Rubricato  varchar(4)='',@CustodiaGaranzia  varchar(1)='',
@Termid varchar(8)='', @Anno decimal(3)=0, @Prog decimal(9)=0
)
RETURNS varchar(123)
AS
BEGIN
	-- Questa funzione concatena i dati dormando una stringa unica
		DECLARE @ResultVar  VARCHAR(123)
		DECLARE @t1 VARCHAR(63)
		DECLARE @tp VARCHAR(5)
		DECLARE @t2 VARCHAR(60)
		declare @AnnoS as varchar(3)
		declare @ProgS as varchar(9)
		set @AnnoS = cast(@Anno as varchar(3))
		set @ProgS = cast(@Prog as varchar(9))
		set @t2= '@'+ rtrim(isnull(@CodInterno, '')) +   rtrim(isnull(@CodMAF, '')) + rtrim(isnull(@CodISIN, '')) + rtrim(isnull(@CodSottoprodotto, ''))
		set @tp  = rtrim(@TipoProdotto)+ '@'
		if len(rtrim(isnull(@Conto, ''))) <12 set @Conto= REPLICATE ( '0' ,12-len(rtrim(isnull(@Conto, ''))) ) +rtrim(isnull(@Conto, ''))
		if len(rtrim(isnull(@Rubricato, ''))) <3 set @Rubricato= REPLICATE ( '0' ,3-len(rtrim(isnull(@Rubricato, ''))) ) +rtrim(isnull(@Rubricato, ''))
		if len(rtrim(isnull(@CustodiaGaranzia, ''))) <1 set @CustodiaGaranzia= '0' 
		if len(rtrim(isnull(@NumeroPolizza, ''))) <11 set @NumeroPolizza= REPLICATE ( '0' ,11-len(rtrim(isnull(@NumeroPolizza, ''))) ) +rtrim(isnull(@NumeroPolizza, ''))
		if len(rtrim(isnull(@Termid, ''))) <8 set @Termid= REPLICATE ( '0' ,8-len(rtrim(isnull(@Termid, ''))) ) +rtrim(isnull(@Termid, ''))
		if len(rtrim(isnull(@AnnoS, 0))) <3 set @AnnoS= REPLICATE ( '0' ,3-len(rtrim(isnull(@AnnoS, 0))) ) +rtrim(isnull(@AnnoS, 0))
		if len(rtrim(isnull(@ProgS, 0))) <9 set @ProgS= REPLICATE ( '0' ,9-len(rtrim(isnull(@ProgS, 0))) ) +rtrim(isnull(@ProgS, 0))
		set @t1= rtrim(isnull(@CodiceContratto,'e'))+rtrim(isnull(@Conto,'e'))+ rtrim(isnull(@Rubricato,'e'))+ 
			rtrim(isnull(@CustodiaGaranzia, 'e'))+ rtrim(isnull(@NumeroPolizza,'e'))+rtrim(isnull(@Termid, 'e'))+
			rtrim(isnull(@AnnoS, 'e'))+rtrim(isnull(@ProgS, 'e'))
		set @ResultVar = isnull(@tp,'tp')  +isnull(@t1,'1') + isnull(@t2,'2')
	-- Return the result of the function
	RETURN @ResultVar
END