0

我有一个具有这种语法的查询

coalesce(cast([tb_groups].[f_member_id_creator] as varchar) + ',', '') + coalesce(cast([tb_groups].[f_member_id_officer1] as varchar) + ',','') + coalesce(cast([tb_groups].[f_member_id_officer2] as varchar) + ',', '') + coalesce(cast([tb_groups].[f_member_id_officer3] as varchar) + ',','') + coalesce(cast([tb_groups].[f_member_id_officer4] as varchar) + ',', '') + coalesce(cast([tb_groups].[f_member_id_officer5] as varchar),'') as admin_list

F_member_id_creator 始终存在于 db 中,但是 f_member_id_officer1 到 5 可以以任意组合使用。

例如,上述语句的返回值可能是

“25431,32663,,,”或“25431,,32663,,”或“25431,,,32663,”或“25431,,,,32663”

等等

我需要做的是告诉 SQL 删除空列表元素并返回“25431,32663”

在 SQL Server 2005 中有什么方法可以做到这一点?

或者更好的是,如果它为空或空白,它是否根本不选择空序数?

4

2 回答 2

0

你得到了结果,因为[tb_groups].[f_member_id_creator],也许是空的,而不是null。试试这个:

coalesce(NULLIF(LTRIM(RTRIM(cast([tb_groups].[f_member_id_creator] as varchar))), '') + ',', '') + ...

如果您同意没有尾随和/或前导空格,则可以省略 LTRIM/RTRIM。

于 2013-09-10T08:58:49.973 回答
0

我稍微修改了上面的代码......我认为它有效......因为它对我有用

COALESCE(CAST([tb_groups].[f_member_id_creator] as varchar), '') + 
COALESCE(NULLIF(',' + CAST([tb_groups].[f_member_id_officer1] as varchar),','), '') + 
COALESCE(NULLIF(',' + CAST([tb_groups].[f_member_id_officer2] as varchar),','), '') + 
COALESCE(NULLIF(',' + CAST([tb_groups].[f_member_id_officer3] as varchar),','), '') + 
COALESCE(NULLIF(',' + CAST([tb_groups].[f_member_id_officer4] as varchar),','), '') + 
COALESCE(NULLIF(',' + CAST([tb_groups].[f_member_id_officer5] as varchar),','), '') as admin_list
于 2013-09-10T10:20:52.993 回答