将SQL字符串别名组合为逗号分隔的字符串

时间:2017-08-11 12:49:52

标签: sql sql-server-2008 stored-procedures reporting-services concatenation

我正在处理这个存储过程,它检查哪些BIT字段为真,并根据它使用别名为其分配文本。我希望能够组合这些别名值(字符串)并以逗号分隔,我可以在我的SSRS报告中显示它。 下面是我存储过程的一部分。

 ,CASE
  WHEN sr.[ReservationAlreadySentAttached] = 1 THEN 'Reservation Already Sent'
  END                           AS ReservationAttached

  ,CASE
  WHEN sr.[HPOfficeAttached] = 1 THEN 'H&P Office'
  END                           AS HPOfficeAttached

  WHEN sr.[NotesAttached] = 1 THEN 'Notes'
  END                           AS NotesAttached

  ,CASE
  WHEN sr.[OpPermitAttached] = 1 THEN 'Op Permit'
  END                           AS OpPermitAttached

  ,CASE
  WHEN sr.[TestResultsAttached] = 1 THEN 'Test Results'
  END                           AS TestResultsAttached

  ,CASE
  WHEN sr.[ConsultationReportsAttached] = 1 THEN 'Consultation Reports'
  END                           AS ConsultationReportsAttached

  ,CASE
  WHEN sr.[OtherAttached] = 1 THEN 'Other'
  END                           AS OtherAttached

所以,假设只有NotesAttached和ReservationAlreadySentAttached才是真正的,那么我希望最终结果以Notes,Reservation Already Sent的形式出现。 我如何连接这些别名?

1 个答案:

答案 0 :(得分:1)

另一种选择是构建你的字符串,然后用STUFF()

删除前导逗号

示例(缩写)

Declare @YourTable table (ReservationAlreadySentAttached bit,HPOfficeAttached bit,NotesAttached bit)
Insert Into @YourTable values
(1,0,1)

Select NewValue = stuff(
                   case when ReservationAlreadySentAttached = 1 then ', Reservation Already Sent' else '' end
                  +case when HPOfficeAttached               = 1 then ', H&P Office'               else '' end
                  +case when NotesAttached                  = 1 then ', Notes'                    else '' end
                  ,1,2,'')
 From  @YourTable

<强>返回

NewValue
Reservation Already Sent, Notes
  

编辑 - 只是表达

 NewValue = stuff(
                   case when sr.[ReservationAlreadySentAttached] = 1 then ', Reservation Already Sent' else '' end
                  +case when sr.[HPOfficeAttached]               = 1 then ', H&P Office'               else '' end
                  +case when sr.[NotesAttached]                  = 1 then ', Notes'                    else '' end
                  ,1,2,'')