title: Execute sub query dependant on parameter/variable
body: <h2>My Question</h2>
  
  <p>I am trying to execute a query within a <code>MERGE</code> query in order to pull results from one table into another. This all works fine apart from one little hickup...</p>
  
  <p>The query that is executed to get the data from the table is dependant on a variable called <code>@User_ID</code>.</p>
  
  <p>If <code>@User_ID</code> is <code>NULL</code> then execute subquery A, else execute subquery B.</p>
  
  <p>The issue that I have is that I do not know how to place an <code>IF</code> within a subquery... How can I do this?</p>
  
  <h2>What I have tried...</h2>
  
  <p>This is what I have so far:</p>
  
  <p><em><strong>Please note, this may work but as I am running SQL Server 2008 not 2012 (I think), the <code>IIF</code> function is not available I think, so I need another method of achieving this.</em></strong></p>
  
  <pre><code>-- Get the relevant logins for the past 12 weeks and insert
  -- them into the temporary table where the week number is the same
  MERGE INTO #Number_Of_Logins AS NOL
  USING (
      SELECT IIF (ISNULL(@User_ID,0), (
              SELECT 
                  Year(UA.Audit_When) AS Year_Num,
                  DatePart(wk, UA.Audit_When) AS Week_Number,
                  Count(*) AS Num_Logins
              FROM User_Auditing UA
              WHERE Audit_Type = 'SYSLI'
                  AND User_ID = @User_ID
                  AND DATEDIFF(wk, Audit_When, GETDATE()) &lt;= 11
              GROUP BY Year(Audit_When), DatePart(wk, Audit_When)
          ),
          (
              SELECT 
                  Year(UA.Audit_When) AS Year_Num,
                  DatePart(wk, UA.Audit_When) AS Week_Number,
                  Count(*) AS Num_Logins
              FROM User_Auditing UA
                  JOIN User_Profiles UP ON UA.User_ID = UP.User_ID
              WHERE UA.Audit_Type = 'SYSLI'
                  AND UP.Company_ID = @Company_ID
                  AND DATEDIFF(wk, UA.Audit_When, GETDATE()) &lt;= 11
              GROUP BY Year(Audit_When), DatePart(wk, UA.Audit_When)
          )
      )
  ) AS TEST
  ON NOL.Week_Number = TEST.Week_Number
  WHEN MATCHED THEN
  UPDATE
      SET Number_Of_Logins = Num_Logins;
  </code></pre>
  
  <h2>Update</h2>
  
  <p>I have also tried using <code>CASE</code>, and I get the following error:</p>
  
  <blockquote>
    <p>An expression of non-boolean type specified in a context where a
    condition is expected, near 'THEN'.</p>
  </blockquote>