I want to know if I can add a join in to a SQL statement based on a an IF statement. I’ve got a query with three variables and I only want to include the join if the third variable is actually filled in. This is my query:
-- Returns all new woksteps for a given time period
-- Includes the ability to narrow down to a specific arrangment
DECLARE @start_added_date DATETIME
DECLARE @end_added_date DATETIME
DECLARE @arrang_part_key INT
SET @start_added_date = '1/4/2011'
SET @end_added_date = '1/5/2011'
SET @arrang_part_key = '1230631'
-- Compensate for CST in the database
SET @end_added_date = DATEADD(DAY, 1, @end_added_date)
SELECT DISTINCT
PWS.Part_Work_Step_Key,
O.Operation_Code,
WS.Work_Step,
PWS.Sort_Order,
U.User_ID,
PWS.Added_Date,
PWS.Cycle_Time,
ET.ECR_Type,
E.ECR_No,
PWS.Effective_Date,
P.Part_No,
P.Revision,
P.Name
FROM Part_V_Part_Work_Step PWS
JOIN Part_V_Work_Step WS
ON WS.Work_Step_Key = PWS.Work_Step_Key
JOIN Part_V_Operation O
ON O.Operation_Key = PWS.Operation_Key
JOIN User U
ON U.User_No = PWS.Added_By
JOIN Part_V_ECR E
ON E.ECR_Key = PWS.Effective_ECR_Key
JOIN Part_V_ECR_Type ET
ON E.ECR_Type_Key = ET.ECR_Type_Key
JOIN Part_V_Part_Work_Step_BOM PWSB
ON PWSB.Part_Work_Step_Key = PWS.Part_Work_Step_Key
JOIN Part_V_BOM B
ON B.BOM_Key = PWSB.BOM_Key
JOIN Part_V_Part P
ON P.Part_Key = B.Part_Key
IF @arrang_part_key IS NOT NULL
BEGIN
JOIN
(
SELECT
AGP.Part_Key
FROM Part_V_Flat_BOM FB
JOIN Part_V_Part AGP
ON AGP.Part_Key = FB.Component_Part_Key
JOIN Part_V_Part_Group PG
ON AGP.Part_Group_Key = PG.Part_Group_Key
AND PG.Part_Group = 'Engineering Group'
WHERE FB.Part_Key = @arrang_part_key
) AG
ON AG.Part_Key = P.Part_Key
END
WHERE PWS.Part_Key IS NULL
AND PWS.Added_Date BETWEEN @start_added_date AND @end_added_date
AND PWS.Active = 1
ORDER BY
O.Operation_Code,
PWS.Sort_Order
But when I run the query I get this as my result:
Error: Incorrect syntax near the keyword 'JOIN'
Error: Incorrect syntax near 'AG'
I am beginning to think that this isn’t the right approach to solving my problem. The query is trying to kill two birds with one stone, return all results for a given time frame, and then allow for filtering down to a specific arrangement if supplied.
OK, so adding a join by an IF block simply cannot work. But I’ve found a way to do my query as well as utilize as much re-usable code as I could think of.
There were two key elements to the query:
To accomplish this I used a combination of both a Table Variable and a CTE (Common Table Expression) and then placed two queries in to my if..else block.
The new query looks like this:
The table variable will always be created and populated with the relevant records for the date range. The IF..Else block will check for an additional arrangement key and create the additional CTE if needed and filter accordingly.