Link to home
Start Free TrialLog in
Avatar of Scott Baldridge
Scott Baldridge

asked on

Concat Notes with OUTER APPLY

Hello, I have the following Outter Apply that is used to get 1 of possible many notes. I need to change statement to concatenate all the notes while adding a visible separator which could be a line break some ***** and a line break to have separation between notes. What would be the best way to accomplish? How to modify the following?

OUTER APPLY (                              
                                    SELECT TOP(1) n.NoteText  
                                          FROM OBJECT_NOTE n
                                          WHERE n.NoteType = 4
                                          AND n.OwnerObjectRegistryId = cs.ObjectRegistryId
                                          ORDER BY n.EntryDate DESC       
                                    )
                        AS FrsNote
Avatar of ste5an
ste5an
Flag of Germany image

Use FOR XML. E.g.

DECLARE @Result VARCHAR(MAX);

SET @Result = ( SELECT	STUFF((SELECT	', ' + name
	FROM	sys.tables
	FOR XML PATH('')), 1, 2, '' ));
PRINT @Result;

PRINT '----';

DECLARE @Terminator VARCHAR(255) = '||***';
SET @Result = ( SELECT	REPLACE(STUFF((SELECT	@Terminator + name
	FROM	sys.tables
	FOR XML PATH('')), 1, LEN(@Terminator), '' ), '||', CHAR(13) + CHAR(10)));
PRINT @Result;

Open in new window

Avatar of Scott Baldridge
Scott Baldridge

ASKER

Not doing XML, the outer apply is part of a much larger select statement where it returns one value. I need that value to be a concatenation of multiple NoteText from the outer apply join condition. Or am I missing something with your solution?
Where is the first part of this outer apply?
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for your assistance!
A small note of caution here. Because this concatenation technique is using XML then IF your data contains characters that XML needs, you can end up with "XML entities" in the output

e.g. IF the data was
"Peter, Paul & Mary"             it could end up looking like
"Peter, Paul & Mary"

To protect against this just tweak the for xml path approach as shown below

SELECT
      T.name
    , X.x
FROM sys.tables T
      OUTER APPLY (
            SELECT
                  STUFF((
                        SELECT
                              ', ' + C.name
                        FROM sys.columns C
                        WHERE C.object_id = T.object_id
                        FOR xml PATH (''), TYPE --<< note
                  )
                  .value('.', 'varchar(max)') --<< note
                  , 1, 2, '')
      ) X (x);