DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX),@LOCALEID char(10);
SET @LOCALEID = '2052'
SELECT @columns = COALESCE(@columns + ',', '') + CONCAT('',t0.FFLEXNUMBER)
FROM T_BAS_FLEXVALUES t0
WHERE t0.FDOCUMENTSTATUS = 'C' AND t0.FFORBIDSTATUS = 'A'

SET @SQL = N'
SELECT 
    t0.FID
    ,t0.aColumn
    ,t0.aValue
    ,t1e_l.FNAME
    ,ROW_NUMBER() OVER (PARTITION BY t0.FID ORDER BY t1.FNUMBER) AS RowId
FROM 
    (SELECT FID,'+@columns+'
     FROM T_BAS_FLEXVALUESDETAIL) AS P
UNPIVOT
    (aValue FOR aColumn IN 
      ('+@columns+')
    )AS t0
    INNER JOIN T_BAS_FLEXVALUES t1 on t1.FFLEXNUMBER = t0.aColumn
    INNER JOIN T_BAS_FLEXVALUESENTRY_L t1e_l on t0.aValue = t1e_l.FENTRYID AND t1e_l.FLOCALEID = '+@LOCALEID+'
;';
EXEC(@SQL);

--SELECT * FROM T_BAS_FLEXVALUES
