Skip to content
Advertisement

TSQL – Conditionally “Cross Join” Records

Code (staging sample data):

Detail: @LookupTab is basically a filter that will have either 0, 1, or both values (111 – Option 1 and 112 – Option 2). @DataTab is the actual data in the table (can be huge). The Val field in this table can either be 111 (Option 1), 112 (Option 2), or 223 (Both Options).

Expectations:

If @LookupTab only passes in 111, I want Id’s 1,2,4,5 returned (total 4 rows). Like so

If @LookupTab only passes in 112, I want Id’s 3,4,5 returned (total 3 rows)

If @LookupTab passes in 111 and 112, I want Id’s 1,2,3,4,5 returned, but since Id 4 and 5 are “Both Options”, I want two rows returned for each. Like so

My unsuccessful try:

Advertisement

Answer

What you need is a INNER JOIN like this:

See the demo.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement