简体   繁体   中英

c# how to build a dynamic query in the where condition

This is my query

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

please notice that i have AND F1Camp02930154 = 'Support'

Now I have a list like this:

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

the values in this list should be in this conidtion AND F1Camp02930154 = 'Support'

for example if the list is empty, i will get an empty result, but if the list has just one value which is Support the query will be

AND F1Camp02930154 = 'Support'

but if the list has two vaules which are Support and Sales then the query will be

AND F1Camp02930154 = 'Support' and `Sales`

how to do that please in c#

where I already have this:

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

Update 1

After @ Gordon Linoff comment

I tried this:

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 += ")";

You can use String.Join() to construct IN () clause, for example :

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM