carriage return in sql server 2012

元气小坏坏 提交于 2019-12-13 09:15:06

问题


Hey I am using the following query to display the problem list separated by commas.

SELECT tt.VrNo, STUFF((select ','+ Er1.ErrorDesc 
from ( select * from CallRegErrors )as Main 
left join ErrorMaster ER1 on Main.ErrorCode=ER1.ErrorCode
WHERE (main.VrNo = tt.VrNo)
FOR XML PATH('')) ,1,1,'') AS Problemlist

query is giving the output like a,b,c,d etc

But my actual requirement is I want to display each error description in a new line like,
a
b
c
d
etc

I tried the following query for it:

SELECT tt.VrNo, STUFF((select char(13)+char(10)+ Er1.ErrorDesc
from ( select * from CallRegErrors )as Main 
left join ErrorMaster ER1 on Main.ErrorCode=ER1.ErrorCode
WHERE (main.VrNo = tt.VrNo)
FOR XML PATH('')) ,1,1,'') AS Problemlist

and also i have used

SELECT tt.VrNo,Replace(STUFF((select ','+ Er1.ErrorDesc as [text()] from ( select * from CallRegErrors )as Main left join ErrorMaster ER1 on Main.ErrorCode=ER1.ErrorCode WHERE (main.VrNo = tt.VrNo) FOR XML PATH('')),1,1,''),',',char(13)+char(10)) AS Problemlist from (select main.VrNo, Er1.ErrorDesc from ( select * from CallRegErrors )as Main left join ErrorMaster ER1 on Main.ErrorCode=ER1.ErrorCode )as tt group by tt.VrNo but now get the problem list seperated by spaces instead of commas after using the above query

but its does not give the output that i want.

please help..

Thanks in advance


回答1:


I think we need more information before we can help you.

I think you are trying to format the information at the child level in a parent child relationship into a list. You probably saw something like this blog on the web.

However, your query is not correctly formatted.

Is the ErrorMaster (Production.ProductCategory) the parent and CallRegErrors (SUB.ProductCategoryID) the child?

If so just change the query to those table name field names for it to work.

I used the REPLACE function on the overall result to change COMMAS to CR + LF.

-- Sample database
USE AdventureWorks2012
GO

-- Change SQL from www.sqlandme.com for this users problem
SELECT      
    CAT.Name AS [Category],
    REPLACE(STUFF((
        SELECT ',' + SUB.Name AS [text()]                        
        FROM Production.ProductSubcategory SUB
        WHERE SUB.ProductCategoryID = CAT.ProductCategoryID
        FOR XML PATH('') 
        ), 1, 1, '' ), ',', CHAR(13) + CHAR(10))
    AS [Sub Categories]
FROM  Production.ProductCategory CAT

You can only see carriage returns in the output window when the type is set to TEXT in SSMS.

I hope this solves your problem. If not, please write back with more information!!



来源:https://stackoverflow.com/questions/18635697/carriage-return-in-sql-server-2012

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