如何在MySql中使用COALESCE来控制数据

时间:2014-08-11 13:55:16

标签: mysql sql sql-server

这是我的SQL查询

DECLARE @strManualRefundIdList AS VARCHAR(MAX)

SELECT  @strManualRefundIdList = COALESCE(@strManualRefundIdList + '|', '') + CONVERT(VARCHAR(MAX), ManualRefund_strReasonCode)
FROM tblManualRefunds WHERE ManualRefund_lngId IN ( 20 ,21 ,22 )

SELECT @strManualRefundIdList;

这就像枢轴一样,所有行连接在一行中。 相同我需要转换为MySql查询。

我试过这个

SELECT 
  CONCAT(COALESCE(CONCAT(v_strManualRefundIdList, '|'), '') , ( ManualRefund_lngId))                     
INTO 
  v_strManualRefundIdList 
FROM tblManualRefunds 
WHERE Trans_lngId IN ( 20 ,21 ,22 ) ;

但它会引发错误Error Code: 1172. Result consisted of more than one row

如何翻译该查询。我是数据库新手。 请帮我搞清楚。

更新:

我发现的方式是分配到游标并循环并连接它。 但这是唯一的方法吗?还是有更好的方法?

2 个答案:

答案 0 :(得分:2)

SELECT group_concat(ManualRefund_strReasonCode SEPARATOR '|')
FROM tblManualRefunds
WHERE manualRefund_lngId in (20,21,22)

SQL Fiddle

答案 1 :(得分:0)

根据xQbert评论我试过这个

SELECT 
  GROUP_CONCAT(COALESCE(CONCAT('shan', '|'), '') , ( ManualRefund_lngId))                    
INTO 
  @v_strManualRefundIdList 
FROM tblManualRefunds ;

工作正常。 谢谢你...... !!!