SQL创建连接字符串
我有一个名为service entry的表,我试图创建一个连接字符串SQL创建连接字符串,sql,sql-server,Sql,Sql Server,我有一个名为service entry的表,我试图创建一个连接字符串 ID ServiceEntryID PartID Comment ServiceTypeIDs PartDescription 1 2 54 xyz 1 hellothere 2 2 22 howdy 3 33
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~你好~1~xyz|22~你好~null~|
对于值为33的服务条目ID列:
33~xyz~1~uhu
如果条目没有注释,则我不会为其添加null,而如果ServiceTypeId为空,则我将添加null
Select coalesce(partID,'NULL') +'~'+
coalesce(PartDescription,'NULL') +'~'+
coalesce(ServiceTypeIDs,'NULL') +'~'+
coalesce(Comment,'NULL') as DesiredStringFormat
FROM yourTableName
当任何字段为空时,上述内容将替换为“空”
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