title: Converting the nvarchar to int
body: <p>I have google online this question and for the life of me couldn't figure out why this kept throwing errors, any help is appreciated.</p>
  
  <blockquote>
    <p>Conversion failed when converting the nvarchar value 'SELECT @orderid
    = t.orderid FROM  (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY creationdatetime DESC) AS row FROM
    [intranet].[dbo].handbook_appendix_data WHERE id = ' to data type int.</p>
  </blockquote>
  
  <pre><code>DECLARE @sql nvarchar(500)
  DECLARE @table varchar(40)
  SET @table = 'handbook_section_data';
  SET @table = 'handbook_appendix_data';
  
  DECLARE @parentid INT
  DECLARE @id INT
  DECLARE @published INT
  DECLARE @orderid INT
  SET @parentid = 2
  SET @id = -1
  SET @published = 1
  
  SET @sql = N'SELECT @orderid = t.orderid FROM 
  (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY creationdatetime DESC) AS row FROM [intranet].[dbo].'+@table+' WHERE id = '+@id+' AND published = '+@published+') AS t
  WHERE t.published = '+@published+' AND t.row = 1';
  EXEC SP_EXECUTESQL @sql, N'@orderid INT OUTPUT', @orderid = @orderid OUTPUT --Get the OrderID from ID
  
  PRINT @orderid
  </code></pre>