FOR XML PATH and string concatenation

前端 未结 3 590
借酒劲吻你
借酒劲吻你 2020-12-19 10:42

I am trying to create a value that concatenates both hard coded strings and strings created using FOR XML PATH.

SUBSTRING(
(SELECT (\', \' + [value]) 
 FROM          


        
3条回答
  •  有刺的猬
    2020-12-19 10:56

    I think your original attempt is almost there. I do this type of thing all the time using the same FOR XML approach. The solution below solves your exact example and can be easily adapted for other purposes:

    DECLARE @delimiter NVARCHAR(10)
    SET @delimiter = ', '
    
    declare @values TABLE (
        [value] NVARCHAR(25)
    )
    
    declare @otherValues TABLE (
        [otherValue] NVARCHAR(25)
    )
    
    INSERT INTO @values VALUES ('Value1')
    INSERT INTO @values VALUES ('Value2')
    INSERT INTO @values VALUES ('Value3')
    
    INSERT INTO @otherValues VALUES ('OtherValue1')
    INSERT INTO @otherValues VALUES ('OtherValue2')
    INSERT INTO @otherValues VALUES ('OtherValue3')
    
    SELECT
        STUFF(
            (
                SELECT
                    @delimiter + CAST([value] AS NVARCHAR(500)) + '' AS [text()]
                FROM
                    @values
                FOR   
                    XML PATH('')
            ),
            1,
            LEN(REVERSE(@delimiter)), -- Reverse the delimiter string in case it has trailing spaces; LEN() won't count those
            ''
        ) +
        ' text in between my values ' +
        STUFF(
            (
                SELECT
                    @delimiter + CAST([otherValue] AS NVARCHAR(500)) + '' AS [text()]
                FROM
                    @otherValues
                FOR   
                    XML PATH('')
            ),
            1,
            LEN(REVERSE(@delimiter)), -- Reverse the delimiter string in case it has trailing spaces; LEN() won't count those
            ''
        )
    

提交回复
热议问题