如何从 SQL 表中提取 ID 列表作为逗号分隔值字符串? [英] How can I pull a list of ID's from a SQL table as a comma-separated values string?
本文介绍了如何从 SQL 表中提取 ID 列表作为逗号分隔值字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须仅使用符合某些条件的记录从表中提取整数 ID 列表.例如:
I have to pull a list of integer IDs from a table using only records that match some criteria. For example:
Select ProdID From Products Where (ProdType='XYZ');
问题是我必须将它作为一组逗号分隔值返回,以便我可以使用它来选择多选列表中的项目:
The catch is that I have to return it as a set of comma separated values so I can use it to select items in a multi-select list:
111,231,554,112
而不是记录.我不想在我的 C# 代码中这样做 - 我希望它通过这种方式直接从数据库中出来.有什么想法吗?
rather than as records. I do not want to do this in my C# code - I'd like it to come right out of the database via a query this way. Any ideas?
推荐答案
除了@OMG Ponies 方法,您还可以尝试以下 COALESCE 技巧:
In addition to @OMG Ponies method, you could also try this COALESCE trick from:
declare @string nvarchar(255)
select @string = coalesce(@string + ', ', '') + cast(prodid as nvarchar(5))
from products
这篇关于如何从 SQL 表中提取 ID 列表作为逗号分隔值字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文