0

I am using SQL Server Management Studio. I have inherited a query that has a section that looks like:

...
ISNULL(
CASE
    WHEN LOWER(PersonClass.Detail) LIKE '%student%'
    THEN SUBSTRING((
            SELECT DISTINCT
                ' / '+STUDENT_TERM.DEPT_NAME
            FROM Warehouse.STUDENT_TERM STUDENT_TERM
                INNER JOIN Warehouse.TERM TERM
                    ON STUDENT_TERM.TERM_CD = TERM.TERM_CD
                    AND TERM.TERM_START_DT <= @fyEnd
                    AND ISNULL(TERM.TERM_END_DT, GETDATE()) >= @fyStart
            WHERE Persons.DWPersonId = STUDENT_TERM.DWPERSID FOR
            XML PATH('')
    ), 4, 100000)
END, '') AS StudentHome,
...

This is finding a student's "home department". There is the possibility that a student could have more than one home so the above works a bit like MySQL's group_concat.

My question is about an unintended artifact of the query. Several departments have names in the data warehouse that have embedded ampersands & in them like:

A & B

The result of the query though is "HTML encoded" turning "A & B" into "A &amp; B".

If I run the inner query the result is as expected with a simple ampersand and not the encoded form. I am guessing that the FOR XML is doing the encoding.

Is there a way to do the group_concat without having the result encoded?

4
  • You should have a standard library in any language you are using that will convert the html entities back Commented Oct 17, 2019 at 17:55
  • 1
    Rather than SUBSTRING it's often better to use STUFF the remove characters from the start of a string. Commented Oct 17, 2019 at 17:57
  • @Larnu -- why is that? Commented Oct 17, 2019 at 17:59
  • 1
    Because, if the OP did have more than 10000 character's it would be truncated. STUFF would simply be used to replace the first characters, it wouldn't be able to truncate it, @Hogan . Commented Oct 17, 2019 at 18:50

1 Answer 1

1

You can get the value from the xml instead of cast to string:

ISNULL(
CASE
    WHEN LOWER(PersonClass.Detail) LIKE '%student%'
    THEN SUBSTRING((
            SELECT DISTINCT
                ' / '+STUDENT_TERM.DEPT_NAME
            FROM Warehouse.STUDENT_TERM STUDENT_TERM
                INNER JOIN Warehouse.TERM TERM
                    ON STUDENT_TERM.TERM_CD = TERM.TERM_CD
                    AND TERM.TERM_START_DT <= @fyEnd
                    AND ISNULL(TERM.TERM_END_DT, GETDATE()) >= @fyStart
            WHERE Persons.DWPersonId = STUDENT_TERM.DWPERSID FOR
            XML PATH(''),TYPE
    ).value(N'.','nvarchar(max)') , 4, 100000)
END, '') AS StudentHome,
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.