我有一个名为service entry的表,我试图创建一个连接字符串。
ID ServiceEntryID PartID Comment ServiceTypeIDs PartDescription
1 2 54 xyz 1 hellothere
2 2 22 howdy
3 33 54 uhu 1 xyz
所需的字符串格式
PARTID〜PartDescription〜ServiceTypeIDs〜注释
所需字符串值
所以对于值为2的服务条目ID列:
54~hellothere~1~xyz | 22~ howdy~null~ |
表示值为33的服务条目ID列:
33~xyz~1~uhu
如果条目没有注释,那么我不为它添加null,而如果servicetypeids为空,那么我将添加null
答案 0 :(得分: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
答案 1 :(得分:0)
Select coalesce(partID,'NULL') +'~'+
coalesce(PartDescription,'NULL') +'~'+
coalesce(ServiceTypeIDs,'NULL') +'~'+
coalesce(Comment,'NULL') as DesiredStringFormat
FROM yourTableName
当任何字段为NULL时,上面将替换“NULL”一词。