Note that there are some explanatory texts on larger screens.

plurals
  1. POFastest performing way to JOIN a temp table to multiple columns in T-SQL
    primarykey
    data
    text
    <p>I need to write a SQL query to filter a table on 4 potential columns from another table of the filter values. </p> <p>Example of what I am trying to do: </p> <pre><code>-- This table could have anywhere from 1 to 2000 possible rows DECLARE @WidgetOwners TABLE (OwnerID INT PRIMARY KEY) INSERT INTO @WidgetOwners VALUES (5) INSERT INTO @WidgetOwners VALUES (50) INSERT INTO @WidgetOwners VALUES (111) INSERT INTO @WidgetOwners VALUES (12345) INSERT INTO @WidgetOwners VALUES (6) --etc... SELECT w.WidgetID FROM Widgets w WHERE w.SellerManagerID IN (SELECT o.OwnerID FROM @WidgetOwners) OR w.SellerID IN (SELECT o.OwnerID FROM @WidgetOwners) OR w.BuyerManagerID IN (SELECT o.OwnerID FROM @WidgetOwners) OR w.BuyerID IN (SELECT o.OwnerID FROM @WidgetOwners) </code></pre> <p>I am under the impression that the SUB SELECTS in the query above will not perform very well. Is there a better way to do this? Could this be done by LEFT JOINING the @WidgetOwner table multiple times? Does anyone have any recommendations here? </p> <p>Keep in mind that I am stuck with SQL 2000 right now and cannot upgrade at the moment.</p> <p><strong>EDIT - Example 2 (This is something else I am trying)</strong></p> <pre><code>SELECT w2.WidgetID, w2.* -- etc FROM ( SELECT w.WidgetID FROM Widgets w INNER JOIN @WidgetOwners o ON w.SellerManagerID = o.OwnerID UNION SELECT w.WidgetID FROM Widgets w INNER JOIN @WidgetOwners o ON w.SellerID = o.OwnerID UNION SELECT w.WidgetID FROM Widgets w INNER JOIN @WidgetOwners o ON w.BuyerManagerID = o.OwnerID UNION SELECT w.WidgetID FROM Widgets w INNER JOIN @WidgetOwners o ON w.BuyerID = o.OwnerID ) x INNER JOIN Widgets w2 ON x.WidgetID = w2.WidgetID </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload