0

I have a table called service entry and Im trying to create a concatenated string.

ID  ServiceEntryID  PartID  Comment  ServiceTypeIDs  PartDescription
1        2           54      xyz      1               hellothere
2        2           22                               howdy
3        33          54      uhu      1               xyz

Desired String format

PartID~PartDescription~ServiceTypeIDs~Comment

Desired String value

so for service entry ID column with value 2:

54 ~ hellothere ~ 1 ~ xyz | 22 ~ howdy ~ null ~ |

for service entry ID column with value 33:

33 ~ xyz ~ 1 ~ uhu

If the entry does not have a comment then I do not add a null for it whereas if servicetypeids are empty then I will add a null

2
  • just wrap each string to concat in a coalesce(comment,'null') statement. Commented Feb 22, 2013 at 16:20
  • thnaks all for your comments and answers Commented Feb 22, 2013 at 16:28

2 Answers 2

2
SELECT
     ServiceEntryID,
     STUFF(
         (SELECT '|' + CAST(PartID AS VARCHAR(5)) + '~' +
                       PartDescription  + '~' +
                       COALESCE(CAST(ServiceTypeIDs AS VARCHAR(5)), 'NULL')  + '~' +
                       COALESCE(Comment, 'NULL')
          FROM TableName
          WHERE ServiceEntryID = a.ServiceEntryID
          FOR XML PATH (''))
          , 1, 1, '')  AS ResultList
FROM TableName AS a
WHERE ServiceEntryID = 2
GROUP BY ServiceEntryID
Sign up to request clarification or add additional context in comments.

Comments

0
Select   coalesce(partID,'NULL') +'~'+ 
coalesce(PartDescription,'NULL') +'~'+ 
 coalesce(ServiceTypeIDs,'NULL') +'~'+
 coalesce(Comment,'NULL') as DesiredStringFormat
FROM yourTableName

The above will substitute the word 'NULL' when any field is NULL.

http://msdn.microsoft.com/en-us/library/ms190349.aspx

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.