I need to build a function that return a string containing values from a table. So I declare a variable NVARCHAR and I use the following code using concat to add each row to the string.
DECLARE @Comment AS NVARCHAR(max) = ''
SELECT @Comment =
@Comment +
CONCAT (
replace(space(100), N' ', N'-')
,CHAR(13)
,convert(NVARCHAR(100), T.DT, 103)
,N' '
,convert(NVARCHAR(5), T.DT, 114)
,N' - '
,isnull(URESP.N_UTIL + N' ' + URESP.PRE_UTIL, 'System')
,N' : '
,isnull(TA.L_TACTION, T.ACT)
,CHAR(13)
,isnull(T.TXT , N' ')
,CHAR(13)
)
FROM (
SELECT D_CREATION DT
,'Commentaire' ACT
,I_C_UTIL_CREA C_UTIL
,L_COMMENT TXT
FROM ACTIONS
WHERE NO_APPEL = 106984 and C_TACTION = 'I_CR_INT'
) T
LEFT JOIN UTILISATEUR URESP ON URESP.C_UTIL = T.C_UTIL
LEFT JOIN TACTION TA ON TA.C_TACTION = ACT
ORDER BY DT desc
PRINT @Comment
Output:
----------------------------------------------------------------------------------------------------
19/07/2018 08:46 - ROCH Charly : Commentaire
test
I can't understand why the string contain only the first row. While the query under
SELECT T.* FROM (
SELECT D_CREATION DT
,'Commentaire' ACT
,I_C_UTIL_CREA C_UTIL
,L_COMMENT TXT
FROM ACTIONS
WHERE NO_APPEL = 106984 and C_TACTION = 'I_CR_INT'
) T
LEFT JOIN UTILISATEUR URESP ON URESP.C_UTIL = T.C_UTIL
LEFT JOIN TACTION TA ON TA.C_TACTION = ACT
ORDER BY DT desc
returns the 2 rows.
DT ACT C_UTIL TXT
2018-07-19 08:50:41.470 Commentaire 14254 test2
2018-07-19 08:46:51.240 Commentaire 14254 test