Dynamic query Join

RoyB09 306 Reputation points
2023-01-23T17:20:11.99+00:00

hello

I have a temp table (@MyTable1) that is populated from an SSRS Multi-select parameter. The table is joined back to another table to output from a stored procedure as follows …

 

JOIN @MyTable1 As b ON b.ItemID=v.ItemID

 

In the Multi Select parameter there is a value ‘_NULL’. If this is the only value selected into @MyTable1, I need to change the JOIN to a LEFT JOIN

 

i.e. 

JOIN @MyTable1 As b ON b.ItemID=v.ItemID becomes  

LEFT JOIN @MyTable1 As b ON b.ItemID=v.ItemID

 

Is there a way to achieve this without a dynamic SQL statement?

Thanks in advance

Roy

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,992 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 112.7K Reputation points MVP
    2023-01-25T22:23:44.6933333+00:00

    So if @MyTable is empty, you want all rows, but if there are values, you only want the matches?

    The simple-minded solution would be:

    IF NOT EXISTS (SELECT * FROM @MyTable) 
       SELECT ... FROM dbo.DataTable
    ELSE 
    BEGIN
       SELECT ...
       FROM   dbo.DataTaable dt
       WHERE  dt.item IN (SELECT t.item FROM @MyTable t)
    END
    

    If you have more conditions of this kind, so that it gets impractical with multiple statements, you can do:

    SELECT @hasvalues = IIF(EXISTS (SELECT * FROM @MyTable), 1, 0)
    
    SELECT ...
    FROM   dbo.DataTaable dt
    WHERE  (@hasvalues = 0 OR dt.item IN (SELECT t.item FROM @MyTable t)
    
    1 person found this answer helpful.

5 additional answers

Sort by: Most helpful
  1. Erland Sommarskog 112.7K Reputation points MVP
    2023-01-24T21:57:41.0266667+00:00

    I'm still not sure that I understand. But it seems that you are making things unnecessarily difficult. Or there is something you have yet to tell us...

    Anyway, from what you have said this far, scrap that dummy value and just let the table variable be empty when the user makes no choices. Then the query can be:

    SELECT cd.CedingID, *
    FROM dbo.expectation e
    LEFT JOIN @tblCeding cd ON cd.CedingID=e.complying_fund_id
    
    

    You will get back all rows in dbo.expectation, and if there is a match in the multi-select thing, you will also get values in cd.CedingID. If there are multiple matches in @tblCedeing, the rows in dbo.expectation will be duplicated.

    But I am not really sure that I understand what you want to achieve with your query. It could help if you post CREATE TABLE statements for your table (simplified to focus at the problem), INSERT statements with sample data, and the desired result given the sample. Finally, a brief explanation why you want that result.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.