COALESCE截断连接输出

时间:2012-09-18 12:59:48

标签: sql-server-2008 sql-server-2008-r2

在最近的帖子Sql server rtrim not working for me, suggestions?中,我从一个选择查询中获得了一个csv字符串。它虽然行为出乎意料,但我找不到任何相似的例子或文档。查询返回没有coalesce语句的802记录,作为普通选择。通过合并,我只回到了81.如果我输出到文本或输出到文件,我会得到相同的结果。此查询返回800多行:

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

但是当我尝试连接这些值时,很多都丢失了:

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

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

1 个答案:

答案 0 :(得分:2)

这应该可以正常工作,但是我会这样做:

DECLARE @str VARCHAR(MAX) = '';

SELECT @str += ',' + LTRIM(RTRIM(Symbol))
FROM dbo.tblDailyPricingAndVol
WHERE Volume > 1000000 AND Clse <= 40 AND radeDate = @maxDate
ORDER by Symbol;

SET @str = STUFF(@str, 1, 1, '');

要确定字符串是否完整,请停止在Management Studio中查看输出。如果超过Management Studio将显示的字符数,则始终将被截断。您可以运行几个测试来检查变量,而不是完整地检查它:

一个。将各个部分的数据长度与结果的数据长度进行比较。

SELECT SUM(DATALENGTH(LTRIM(RTRIM(Symbol)))) FROM dbo.tblDailyPricingAndVol
  WHERE ...

-- concatenation query here

SELECT DATALENGTH(@str);

-- these should be equal or off by one.

B中。将变量的结尾与集合中的最后一个元素进行比较。

SELECT TOP 1 Symbol FROM dbo.tblDailyPricingAndVol
  WHERE ...
  ORDER BY Symbol DESC;

-- concatenation query here

SELECT RIGHT(@str, 20);

-- is the last element in the set represented at the end of the string?