You can concatenate the values of a field from multiple rows into a single text string in SQL Server by using the FOR XML PATH and STUFF functions. Here's an example of how to do it:
DECLARE @StringVariable VARCHAR(MAX)
SELECT @StringVariable = STUFF((SELECT ', ' + names
FROM User
FOR XML PATH('')), 1, 2, '')
SELECT @StringVariable AS ConcatenatedString
In this example, the FOR XML PATH function is used to concatenate the values of the names field, separated by a comma and a space. The STUFF function is used to remove the first two characters (', ') from the concatenated string. The result is then stored in the @StringVariable variable and can be returned as the ConcatenatedString field.
Posted On:
12-Feb-2023 08:16