I have a table where it can have multiple records with same id and I want to make it single string. Here in stack overflow I found some examples which shows the use of either CAST
or CASE
.
I tried both of them but none of them seems to work. Meaning, query works but returns result in separate lines. I couldn't figure our what am I missing here?
Query - 1: Using CAST
SELECT DISTINCT
c.Name AS CallCenter,
LTRIM(RTRIM(s.Name)) Name,
d.DNIS,
s.ScriptId,
CAST(sL.Line + ';' AS VARCHAR(MAX)) AS Script ,
sL.ScriptLineId
FROM CallCenterScript s WITH (NOLOCK)
LEFT JOIN CallCenterScriptLine sL WITH (NOLOCK) ON sL.ScriptId = s.ScriptId
INNER JOIN CallCenterDNIS d WITH (NOLOCK) ON d.ScriptId = s.ScriptId
INNER JOIN CallCenter c WITH (NOLOCK) ON c.Id = s.CallCenterId
WHERE (s.IsDeleted = 0 OR s.IsDeleted IS NULL)
ORDER BY DNIS ASC
Query - 2: Using CASE
DECLARE @Result VARCHAR(MAX);
SELECT DISTINCT
c.Name AS CallCenter,
LTRIM(RTRIM(s.Name)) Name,
d.DNIS,
s.ScriptId,
CASE
WHEN @Result IS NULL
THEN sL.Line
ELSE @Result + ';' + sL.Line
END as Script ,
sL.ScriptLineId
FROM CallCenterScript s WITH (NOLOCK)
LEFT JOIN CallCenterScriptLine sL WITH (NOLOCK) ON sL.ScriptId = s.ScriptId
INNER JOIN CallCenterDNIS d WITH (NOLOCK) ON d.ScriptId = s.ScriptId
INNER JOIN CallCenter c WITH (NOLOCK) ON c.Id = s.CallCenterId
WHERE (s.IsDeleted = 0 OR s.IsDeleted IS NULL)
ORDER BY DNIS ASC
Sample:
Expected: