c#如何在where条件中构建动态查询

时间:2014-08-19 10:30:48

标签: c# sql

这是我的查询

SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) 
WHERE MPRO.Estado0154 = 'QUEUED' 
AND F1IdWI02140154<>'VOICEMAIL'
AND F1Camp02930154 = 'Support'

请注意我有AND F1Camp02930154 = 'Support'

现在我有一个这样的列表:

List<string> compaines = new List<string>();

此列表中的值应位于此条件AND F1Camp02930154 = 'Support'

例如,如果列表为空,我将得到一个空结果,但如果列表只有一个Support的值,则查询将

AND F1Camp02930154 = 'Support'

但是如果列表有两个Support and Sales的值,那么查询将是

AND F1Camp02930154 = 'Support' and `Sales`

如何做到这一点请在c#

我已经有了这个:

string queryString = "SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) WHERE MPRO.Estado0154 = 'QUEUED' AND F1IdWI02140154<>'VOICEMAIL'";

更新1

@ Gordon Linoff评论后

我试过了:

List<string> compaines = new List<string>();
            string queryString = "SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) WHERE MPRO.Estado0154 = 'QUEUED' AND F1IdWI02140154<>'VOICEMAIL' AND F1Camp02930154 IN (";
            for (int i = 0; i < compaines.Count(); i++) {
                queryString += "'" + compaines[i] + "'";
            }
            queryString += ")";

1 个答案:

答案 0 :(得分:0)

您可以使用String.Join()构建IN ()子句,例如:

var companies = new List<string>() { "Support", "Sales" };
string inClause = String.Format(" IN ('{0}')", String.Join("', '", companies));
Console.WriteLine("AND F1Camp02930154" + inClause);
//output :
//AND F1Camp02930154 IN ('Support', 'Sales')