title: how to use declare variable in select query in stored procedure using sql server
body: <p>Hello I want to concate two things one is string and other is int variable. Now, these thing I want to store in one variable and use that variable in select query as a into type to create a temptable in stored procedure using sql server.</p>
  
  <p>Here is my query </p>
  
  <pre><code>USE [FlightExamSoftware]
  GO
  SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  -- For Storing Question in Temp table  
  -- EXEC [GetQuestionListPerSubjectRatioWise] 1,11
  ALTER PROCEDURE [dbo].[GetQuestionListPerSubjectRatioWise]
  @SubjectID INT,
  @NumberOfQue INT,
  @UserID int
  AS
  BEGIN
  DECLARE @strQuery VARCHAR(MAX);
  DECLARE @PerChapQue INT;
  
  DECLARE @tempTable VARCHAR(MAX) = 'tempTestUser' + @UserID;
  
  SELECT @PerChapQue = COUNT(appQueID)/@NumberOfQue FROM tblQuestion WHERE appQueSubID=@SubjectID
  
  SELECT COUNT(appQueID)/@PerChapQue ChapwiseQue
      ,CASE WHEN COUNT(appQueID)&gt;=@PerChapQue THEN COUNT(appQueID)/@PerChapQue ELSE 1 END ChapWiseQuePlusOne
      ,appQueChapID into @tempTable
      FROM tblQuestion 
      WHERE appQueSubID=@SubjectID   
      GROUP BY appQueChapID
  END
  </code></pre>
  
  <p>Now, I am talking about these line</p>
  
  <pre><code>DECLARE @tempTable VARCHAR(MAX) = 'tempTestUser' + @UserID;
  </code></pre>
  
  <p>In these line two things are concate one is string and other is int. And store in varchar variable. </p>
  
  <p>And use in following select query i.e.</p>
  
  <pre><code>SELECT COUNT(appQueID)/@PerChapQue ChapwiseQue
      ,CASE WHEN COUNT(appQueID)&gt;=@PerChapQue THEN COUNT(appQueID)/@PerChapQue ELSE 1 END ChapWiseQuePlusOne
      ,appQueChapID into @tempTable
      FROM tblQuestion 
      WHERE appQueSubID=@SubjectID   
      GROUP BY appQueChapID
  END
  </code></pre>
  
  <p>Now, in these query I want to create a temptable named <code>@tempTable</code>. </p>
  
  <p>But, in these line it showing error i.e. <code>Incorrect syntax near '@tempTable'.</code></p>
  
  <p>Confuse that where is the syntax is wrong.</p>
  
  <p>Thank You.</p>