Formatting Results of STUFF command that uses For XML Path to concatenate the information into one cell

隐身守侯 提交于 2019-12-11 20:28:06

问题


I am using a STUFF Command to pull in data from a column and concatenate them together into one cell.

STUFF((Select CAST(v.ID as VARCHAR)+ ', '

From Source

Where CriteriaIsMet
For XML Path('')),1,0,'') as MonitorID

What I am trying to accomplish is formatting the results at the end. The results from the code above come out like this:

 12345, 23456, 34567, 456789,

I am looking for the code to have a line break. I want them all to still be in the same cell and not broken up but when placed in Excel I am hoping to have this be the results:

12345,
23456,
34567,
45678,

I have tried using:

 STUFF((Select REPLACE(CAST v.ID as VARCHAR) + ', ' , ', ', +CHAR(13))

However the end results don't give me what I am looking for I end up with this:

123456
234567&#x0D

I believe I need to do something at the end of the statement to make this happen, however, I am not sure how to accomplish this because I am using:

For XML Path('')),1,0,'') 

I am hoping that someone may have a simple solution. I would greatly appreciate any assistance. Please note I am trying to keep the data in the same cell. The end result of this data pull goes into a Pivot table in Excel and i'd like for the numbers to display vertically rather than horizontally. When displayed Horizontally the numbers cut off after passing the length of the cell.


回答1:


Try this...

SELECT STUFF((Select  CAST(v.ID as VARCHAR(30)) +  + ', '+ CHAR(10)
       From Source
       Where CriteriaIsMet
       For XML Path(''),TYPE)
      .value('.','NVARCHAR(MAX)'),1,0,'') as MonitorID



回答2:


Instead of adding CHAR(13) and/or CHAR(10), CHAR(9) horizontal TAB worked for me. The complete STUFF argument and other possible large text fields should also be CASTED as varchar(255).

Should be something like: SELECT CAST(STUFF((...) + CHAR(9) as varchar(255)) as MonitorID



来源:https://stackoverflow.com/questions/29592810/formatting-results-of-stuff-command-that-uses-for-xml-path-to-concatenate-the-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!