title: Dynamic SQL error converting nvarchar to int
body: <p>I have created a procedure in dynamic SQL which has a select statement and the code looks like:</p>
  
  <pre><code>ALTER PROCEDURE cagroup    (
      @DataID INT ,
      @days INT ,
      @GName VARCHAR(50) ,
      @T_ID INT ,
      @Act BIT ,
      @Key VARBINARY(16)
  )
  AS
  BEGIN
      DECLARE @SQL NVARCHAR(MAX)
      DECLARE @SchemaName SYSNAME
      DECLARE @TableName SYSNAME
      DECLARE @DatabaseName SYSNAME
      DECLARE @BR CHAR(2)
      SET @BR = CHAR(13) + CHAR(10)
  
      SELECT  @SchemaName = Source_Schema ,
              @TableName = Source_Table ,
              @DatabaseName = Source_Database
      FROM    Source
      WHERE   ID = @DataID
  
  SET @SQL =  'SELECT ' + @GName + ' AS GrName ,' + @BR
                  + @T_ID + ' AS To_ID ,' + @BR
                  + @DataID + ' AS DataSoID ,' + @BR
                  + @Act + ' AS Active ,' + @BR
                  + Key + ' AS key' + @BR
                  + 'R_ID AS S_R_ID' + @BR
                  + 'FROM' + @DatabaseName + '.'
                  + @SchemaName + '.'
                  + @TableName + ' t' + @BR
                  + 'LEFT OUTER JOIN Gro g ON g.GName = '
                      + @GName + @BR + 'AND g.Data_ID] =' + @DataID + @BR
                      + 't.[I_DATE] &gt; GETDATE() -' + @days + @BR
                      + 'g.GName IS NULL
                          AND ' + @GName + ' IS NOT NULL
                          AND t.[Act] = 1' + @BR
  
      PRINT (@SQL)
  END
  </code></pre>
  
  <p>When I am executing this procedure with this statement:</p>
  
  <pre><code>Exec  dbo.cagroup  1,10,'[Gro]',1,1,NULL
  </code></pre>
  
  <p>I am getting the following error.</p>
  
  <blockquote>
    <p>Msg 245, Level 16, State 1, Procedurecagroup, Line 33
    Conversion failed when converting the nvarchar value 'SELECT [Gro] AS GName ,
    ' to data type int.</p>
  </blockquote>
  
  <p>Where am I doing wrong?</p>