﻿CREATE FUNCTION [dbo].[Crea_positionID_test]
(
	@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 formando 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))
	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(@t1,'1') 
	SET @ResultVar = '2'
	-- Return the result of the function
	RETURN @ResultVar
END