带STR功能的前导space

Leading space with STR function

我需要一个逗号分隔的引号列表,我快到了,但我得到一个逗号列表,但开头有一个前导 space,但在第一个引号和字符串之间.

select stuff((select distinct ','+''''+str(bid)+'''' from dbo.Companies
where IdCompany in (select substring(ID_COMPANY,1,LEN(ID_COMPANY)-2)  from
sql.Companies where SEGMENT = @Segment and STATE = 'ACTIVE')
FOR XML PATH('')) , 1 , 1 , '' )

我得到这样的结果:

' 500004600',' 500005200',' 500009600',' 500021500'

如何删除左边的 space 以便得到:

'500004600','500005200','500009600','500021500'

这是 STR() 函数上的 documented

length

Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.

您尚未指定值,因此将其间隔为 10。

您应该 CAST 改为 varchar。一个更简单的选择,当你有连接时,使用 CONCAT 也将转换它。

You should also remove the DISTINCT and use GROUP BY bid, otherwise indexes and other optimizations cannot be used (because of the concatenation).

SELECT STUFF((
    SELECT CONCAT(',''', c.bid, '''')
    FROM dbo.Companies c
    WHERE c.IdCompany in (
        SELECT SUBSTRING(c2.ID_COMPANY, 1, LEN(c2.ID_COMPANY) - 2)
        FROM sql.Companies c2
        WHERE c2.SEGMENT = @Segment
          AND c2.STATE = 'ACTIVE'
    )
    GROUP BY
      c.bid
    FOR XML PATH('')
  ) , 1 , LEN(',') , '' )

附带一点,如果您要连接可能存在 XML 转义问题的字符串,则需要

    FOR XML PATH(''), TYPE
  ).value('text()[1]','varchar(max)') , 1 , LEN(',') , '' )

显然,在较新版本的 SQL 服务器中,您可以只使用 STRING_AGG

 SELECT STRING_AGG(CONCAT('''', c.bid, ''''), ',')
 FROM dbo.Companies c
 WHERE c.IdCompany in (
     SELECT SUBSTRING(c2.ID_COMPANY, 1, LEN(c2.ID_COMPANY) - 2)
     FROM sql.Companies c2
     WHERE c2.SEGMENT = @Segment
       AND c2.STATE = 'ACTIVE'
 )
 GROUP BY
   c.bid