简体   繁体   English

sql server rtrim不适合我,建议?

[英]Sql server rtrim not working for me, suggestions?

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. 我想将数据放入csv文件中。 I'm happy to copy/ paste the results from SSMS "results to text" if that's easier. 我很乐意将结果从SSMS“结果复制/粘贴到文本”中复制/粘贴,如果这更容易的话。 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. 等。在S.Symbol油田周围的Rtrim没有帮助。 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.. 一如既往地感谢...

p.Symbol is defined as CHAR(8), and CHAR values cannot be trimmed. p.Symbol定义为CHAR(8),并且不能修剪CHAR值。 Convert to N/VARCHAR(8) before trimming. 在修剪之前转换为N / VARCHAR(8)。

From your expected result, it seems that you want to concatenate the symbol value from all the rows into one comma demimited string. 根据您的预期结果,您似乎希望将所有行中的symbol值连接成一个逗号分隔的字符串。

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. 关于你的RTRIM的问题,这看起来很奇怪。 To be on the safe side, i have added LTRIM + RTRIM to the above query. 为了安全起见,我已将LTRIM + RTRIM添加到上述查询中。 However, as long as your symbol column is some kind of varchar , there is really no reason for the RTRIM to not work. 但是,只要您的symbol列是某种varcharRTRIM就没有理由不起作用。

Can you clarify the datatype of symbol column in your table? 你能澄清一下表格中symbol列的数据类型吗?

Since you are using SQL server 2008, you could do this: 由于您使用的是SQL Server 2008,因此可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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