title: Conditional UNION in stored procedure
body: <p>Bonjour!</p>
  
  <p>So, in a stored procedure I would like to do a conditional union decided by a parameter.
  How can I do that?</p>
  
  <p>Here is my "doesn't work" procedure :</p>
  
  <pre><code>SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  
  
  CREATE PROCEDURE [dbo].[spp_GetAdressesList]
  
      @OnlyLinked   bit         = 1,    
      @ObligedId    int         = -1 
  AS 
  BEGIN
  
      SELECT 
         [ID_ADRESS]
        ,[ID_ENT]
        ,[VOI_ADRESS]
        ,[NUM_ADRESS]
        ,[BTE_ADRESS]
        ,[CP_ADRESS]
        ,[VIL_ADRESS]
  
      FROM [ADRESSES]
      WHERE  
      (
  
          (VIL_ADRESS != 'NC' AND VIL_ADRESS != '--')
          AND
          (@OnlyLinked = 0 OR ID_ENT is not null)
  
      )
  
      IF (@ObligedId != -1)
      BEGIN
          UNION
              SELECT 
                 [ID_ADRESS]
                ,[ID_ENT]
                ,[VOI_ADRESS]
                ,[NUM_ADRESS]
                ,[BTE_ADRESS]
                ,[CP_ADRESS]
                ,[VIL_ADRESS]
  
              FROM [ADRESSES]
              WHERE  
              ID_ADRESS = @ObligedId
      END
  
  END
  </code></pre>
  
  <p>So if @ObligedId est =  a -1 I would like to doesn't have the UNION.</p>
  
  <p>I made this with a dynamic varchar query, at the end I was executing the query with an exec. But it's apparently less efficient and you can make sql injection (It is for asp.net application) with dynamic queries. I decided to change all my stored procedures</p>
  
  <p>It's not possible to do an union in a IF clause?</p>
  
  <p>Thanks for all answers without exceptions..</p>