简体   繁体   中英

converting rows to one column sql server

i am using the following query to convert rows to column

SELECT STUFF((SELECT NAME + ',' FROM TABLE1
FOR XML PATH('')),1,0,'') AS [ACCOUNT NAMES]

the table have the follwing data

NAME 
-------------------
GURPREET & CO.
SIMRAN TRADERS
LABOUR & WELFARE
-------------------

i want the output like

GURPREET & CO., SIMRAN TRADERS, LABOUR & WELFARE,

but the sql given the output

GURPREET &amp CO., SIMRAN TRADERS, LABOUR &amp WELFARE,

how can i remove &amp?

Since you're keeping the final comma in your example, you don't need the STUFF, especially if you're using it with parameters ,1,0,'' which is a no-op.

SELECT
    (SELECT NAME + ','
       FROM TABLE1
        FOR XML PATH(''),type).value('.','nvarchar(max)') AS [ACCOUNT NAMES]

If you did want to remove the last comma, then it should be like this:

SELECT STUFF(
    (SELECT ',' + NAME
       FROM TABLE1
        FOR XML PATH(''),type).value('.','nvarchar(max)'),1,1,'') AS [ACCOUNT NAMES]

Note: The problem is that you're using a common pattern that is almost as old as the internet, which did not account for XML entitisation. Using the FOR XML TYPE specifier keeps the original text when extracted again via .value, varchar(max) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM