I have some option-item combination in my application from which the user can choose from, and hence to be queried from SQL Server to fetch some results
Let’s say the user choose combination like:
Option1 - Item1
Option1 - Item2
Option2 - Item1
Database table:
Option1 Item1 Details1 Details2 Details3
Option1 Item2 Details4 Details5 Details6
Option1 Item3 Details7 Details8 Details9
Option1 Item4 Details10 Details11 Details12
...
Option2 Item1 Details13 Details14 Details15
On selecting, the above option-item combination, their corresponding details are to be retrieved.
How do I fetch these details by passing in the Option-Item combination in the query?
I tried something like:
SELECT * FROM tbData
WHERE Strategy IN ('Option1','Option2')
AND Items IN ('Item1','Item2')
…but this gives the wrong answer.
You can’t use
INlike that. You need to say:This is because
INon each column separately means “return any rows where strategy is any value in (option 1 or option 2), and items is any value in (item 1 or item 2).” You can’t apply those two concepts separately and expect SQL Server to know that Item2 only applies to Option1.Now, another option is to use a table-valued parameter. So you can define a table type as follows in SQL Server:
Populate a DataTable in C# with the selected options, then pass that in. Your query becomes:
EDIT adding yet another option.
If you can pass the set of options into your table as a dual-delimited string, e.g.
Then you could use a table-valued function, e.g.
So now you can say:
And then call the stored procedure this way (by passing this comma/semi-colon-delimited string from your application):
But I still think the TVP option is the way to go.