title: Creating procedure inside IF section
body: <p>I need some help with simple SQL code:</p>
  
  <pre><code>DECLARE @procExists int
  SET @procExists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = 'dbo' AND ROUTINE_NAME = 'Table_Exists' AND ROUTINE_TYPE = 'PROCEDURE')
  IF NOT @procExists &gt; 0 
  BEGIN
      -- test query
      -- SELECT 'Something' = @procExists;
  
      -- error throwing code
      -- CREATE PROCEDURE Table_Exists
      --     @schemaName varchar(50),
      --     @tableName varchar(50)
      -- AS
      --     RETURN (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schemaName AND TABLE_NAME = @tableName)
  END
  </code></pre>
  
  <p>The simple code above:<br>
  - declares an int variable<br>
  - checks if procedure dbo.Table_Exists exists<br>
  - IF NOT exists it creates it</p>
  
  <p>My problem is this error information:</p>
  
  <pre><code>Msg 156, Level 15, State 1, Line 9
  Incorrect syntax near the keyword 'PROCEDURE'.
  Msg 137, Level 15, State 2, Line 13
  Must declare the scalar variable "@schemaName".
  </code></pre>
  
  <p>I don't know why, but..<br>
  - when i execute 'CREATE PROCEDURE' body <strong>alone</strong> it works<br>
  - when i execute whole IF section <strong>excluding</strong> 'CREATE PROCEDURE' body, simple query works<br>
  - when i execute whole IF section <strong>including</strong> 'CREATE PROCEDURE' body, error is thrown</p>
  
  <p>What am i missing?</p>