Ali_dotNet
Ali_dotNet

Reputation: 3279

performing a loop operation in SQL server query

I' writing a search function in C# SQL Server, my users can select multiple job groups and this function should check all of the selected group ids in my job table, how can I perform a loop operation in SQL Server? this is my table general schema:

id int, jobname varchar, jobgroup int.....

I use following query to select my jobs (based on jobgroup):

select * from tblJobs where jobgroup='"+userGroups+"'

this can be true only when userGroups contains one value, but my users can select several group ids, for instance my userGroups can be something like this: 5,7,10,20 (userGroups can contain much more values)

how should I perform a loop operation in my query so that I can have all matching jobs? should I concatenate returned values of several queries each selecting one group ID? I think there are better ways

Upvotes: 0

Views: 228

Answers (1)

Oded
Oded

Reputation: 498924

Don't use looping in SQL - loops tend to kill performance of SQL databases.

In this case, I believe the IN clause can do:

SELECT col1, col2 
FROM tblJobs 
WHERE jobgroup IN ('"+userGroups+"', '"+userGroup2+"')

Upvotes: 1

Related Questions