SQL Server how to combine column data to string

Copyright: copy, please indicate the source https://blog.csdn.net/weixin_39392627/article/details/86760993

env:Windows Server 2016

       SQL Server 2016 SP2

Before meeting a demand, the data fields are combined into a string, each separated by commas data needs.

This time we set out directly grammar

1. Using FOR XML syntax to set a binding string syntax

command:

SELECT
    (SELECT CAST([Name] AS NVARCHAR) + ',' FROM [dbo].[TETTB01] for xml path(''))
FROM [dbo].[TETTB01]

 

2. The strings have been combined and are out to make a comma-separated, but the end of the string is a comma, which is part of the next to be processed. End of the string to remove commas.

command:

SELECT 
    LEFT((SELECT CAST([Name] AS NVARCHAR) + ',' FROM [dbo].[TETTB01] for xml path(''))
        ,LEN((SELECT CAST([Name] AS NVARCHAR) + ',' FROM [dbo].[TETTB01] for xml path('')))-1)
FROM [dbo].[TETTB01]

 

 

Guess you like

Origin blog.csdn.net/weixin_39392627/article/details/86760993