title: SQL Server : exclude part of Union in stored procedure conditionally
body: <p>I have a stored procedure like this (shortened to the minimum necessary):</p>
  
  <pre><code>CREATE PROCEDURE [dbo].[proc_Foo]
      -- Add the parameters for the stored procedure here
      @StyleNumber int,
      @App nvarchar(50),
      @User nvarchar(20)
  AS
  BEGIN
      DECLARE @UserChar varchar(1) = 'U'
  
      -- User with App
      SELECT [StyleType],
             [Value], 'UA' AS 'DerivedFrom'
      FROM daten.dbo.GridStyleLocal
      WHERE [StyleAssign] = @UserChar
      AND [User] = @User
      AND [StyleNumber] = @StyleNumber
      AND [Application] = @App
  
      UNION
  
      -- Global (Basis) with app
      SELECT [StyleType],
             [Value], 'GA' AS 'DerivedFrom'
      FROM basis.dbo.GridStyle
      WHERE [StyleNumber] = @StyleNumber
      AND [Application] = @App
      AND [StyleType] NOT IN (
          SELECT [StyleType]
          FROM daten.dbo.GridStyleLocal
          WHERE [StyleAssign] = @UserChar
          AND [User] = @User
          AND [StyleNumber] = @StyleNumber
          AND [Application] = @App)
  
      UNION
  
      -- Scrape missing StyleTypes from Number 0
      SELECT [StyleType],
             [Value], 'G0A' AS 'DerivedFrom'
      FROM basis.dbo.GridStyle
      WHERE [StyleNumber] = 0
      AND [Application] = @App
      AND [StyleType] NOT IN (
          SELECT [StyleType]
          FROM daten.dbo.GridStyleLocal
          WHERE [StyleAssign] = @UserChar
          AND [User] = @User
          AND [StyleNumber] = @StyleNumber
          AND [Application] = @App)
      AND [StyleType] NOT IN (
          SELECT [StyleType]
          FROM basis.dbo.GridStyle
          WHERE [StyleNumber] = @StyleNumber
          AND [Application] = @App)
  
  END
  
  GO
  </code></pre>
  
  <p>Now <code>StyleNumber</code> 0 is my base style. All properties (<code>StyleType</code>) that are not in another <code>StyleNumber</code> are derived from <code>StyleNumber</code> 0. But now if I include the second <code>SELECT</code> (Global (Basis) with app) when <code>@StyleNumber</code> is set to 0, the <code>DerivedFrom</code> value is GA instead of G0A.</p>
  
  <p>So is there a any kind of conditional, that could exclude this <code>SELECT</code> out of the union if <code>@StyleNumber</code> is 0?</p>