title: SQL Server stored procedure if statement injection string
body: <p>Using SQL Server I am trying to inject a string into a SQL statement based on an if statement, note that am trying to accomplish this inside a stored procedure. </p>
  
  <p>I am currently getting an error for this code:</p>
  
  <pre><code>Declare @topString varchar(240)
  
  IF @topRecords &gt; 0
  SET @topString = 'top 500'
  ELSE
  SET @topString = ''
  
  SELECT @topString * FROM( //incorrect syntax near FROM
  
  SELECT  top 500 c.Id as [Customer Id],....
      UNION
      SELECT  top 500 c.Id as [Customer Id],....
  )as table1 
  Order by 1 desc
  </code></pre>
  
  <p><strong>Edit</strong></p>
  
  <pre><code>if somethingTrue
  @whereCondition = '1 = 1 '
  else 
  @whereCondition = branch = @branch
  
  select * from table 
  where @whereCondition AND etc...
  </code></pre>
  
  <p><strong>Correct</strong></p>
  
  <p>for injection inside an if statement go with Jodrell <br />
  but if you need a dynamic top then go with what was suggested by Kaf. <br />
  thanks both for the help!</p>