Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL创建连接字符串_Sql_Sql Server - Fatal编程技术网

SQL创建连接字符串

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

我有一个名为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~你好~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
当任何字段为空时,上述内容将替换为“空”


只需将每个字符串包装到concat中的一个联合(comment,'null')语句中即可。thnak用于您的注释和answers@tamtam很高兴听到这个消息:D
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