从一行中的字符串列表构建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参数,但似乎有很多开销。 有关详细信息,请参阅http://www.sommarskog.se/arrays-in-sql-2008.html 。