从一行中的字符串列表构建SQL“where in”语句?
我有一个List(Of String),对应于数据库表中的“types”。
我们正在使用DB2 ADO.NET提供程序,我的最终查询需要看起来像这样:
select * from table where type in (@type1, @type2, @type3, @type4)
在过去,我使用ForEach循环构建了查询参数/主机变量列表,但我真的想找到一种方法来在一行中构建它们。 当然,我可以加入所有字符串,但添加“@”和递增数字让我感到头疼。
任何人对如何做到这一点都有任何想法?
不会有这样的工作吗?
var inList = "(" + string.Join(", ", typeList.Select(t => "@" + t)) + ")";
编辑
根据你的评论,这个怎么样?
var inList = "(" + string.Join(", ", Enumerable.Range(1, argCount).Select(i +> "@type" + i)) + ")";
使用string.Join(",", listType.ToArray())
拆分列表
string types = string.Join(",", listType.ToArray()); Select * from table where type in (types)
string dbCommand = string.Format("select * from table where type in ({0})", string.Join(",", typeList.Select(p => "@" + p));
SQL / ADO.NET不支持数组。 所以你真的必须手工构建SQL。
SQL 2008确实支持Table参数,但似乎有很多开销。 有关详细信息,请参阅https://www.sommarskog.se/arrays-in-sql-2008.html 。
上述就是C#学习教程:从一行中的字符串列表构建SQL“where in”语句?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1001873.html