Sql server rtrim not working for me, suggestions?

一曲冷凌霜 提交于 2019-12-12 15:31:36

问题


I'm a bit surprised that I can't find a quick solution to what I'm up against, seems like it'd be a common thing to deal with. I can't get rid of the trailing spaces in my select query. I'd like to get the data into a csv file. I'm happy to copy/ paste the results from SSMS "results to text" if that's easier. Either way, my query is:

declare @maxDate date = (select MAX(TradeDate) from tblDailyPricingAndVol)

select p.Symbol, ','
from tblDailyPricingAndVol p
where p.Volume > 1000000 and p.Clse <= 40 and p.TradeDate = @maxDate
order by p.Symbol

and it returns:

A       ,
AA      ,
ABB     ,

etc. Rtrim around the p.Symbol field didn't help. If I could figure out the best solution, I'd have results of:

A,AA,ABB

and so on. Any takers? Thanks in advance as always..


回答1:


From your expected result, it seems that you want to concatenate the symbol value from all the rows into one comma demimited string.

In order to do that, you can do this :-

DECLARE @str VARCHAR(MAX)
SELECT @str = COALESCE(@str+',' ,'') + LTRIM(RTRIM((p.Symbol)))
FROM tblDailyPricingAndVol p
WHERE p.Volume > 1000000 and p.Clse <= 40 and p.TradeDate = @maxDate
ORDER by p.Symbol
SELECT @str
GO

Additional alternate methods can also be referenced here

Regarding your issue with the RTRIM not working, that seems very odd. To be on the safe side, i have added LTRIM + RTRIM to the above query. However, as long as your symbol column is some kind of varchar, there is really no reason for the RTRIM to not work.

Can you clarify the datatype of symbol column in your table?




回答2:


p.Symbol is defined as CHAR(8), and CHAR values cannot be trimmed. Convert to N/VARCHAR(8) before trimming.




回答3:


Since you are using SQL server 2008, you could do this:

SELECT  STUFF((SELECT ', ' + rtrim(p.Symbol)
          from tblDailyPricingAndVol p FOR XML PATH('')),1,2,'') as Symbol
WHERE    p.Volume > 1000000 
AND      p.Clse <= 40 
AND      p.TradeDate = @maxDate
ORDER BY p.Symbol


来源:https://stackoverflow.com/questions/12452403/sql-server-rtrim-not-working-for-me-suggestions

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