Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server 2008 - #tmp table throws error when run within an exec command
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/688161/tsql-writing-into-a-temporary-table-from-dynamic-sql">TSQL Writing into a Temporary Table from Dynamic SQL</a> </p> </blockquote> <pre><code> ALTER PROCEDURE [dbo].[usp_ServicesStats1](@PERIOD VARCHAR(30) ) AS BEGIN -- SET NOCOUNT ON added to prevent extra result SETs FROM -- interfering with SELECT statements. SET NOCOUNT ON; DELETE FROM servicesstats1; DECLARE @QUERY NVARCHAR(MAX); DECLARE @mainTable VARCHAR(50) SET @mainTable = '[ServicesStats' + @PERIOD + ']'; SET @QUERY = 'INSERT INTO servicesstats1(Department,StudentUsers) SELECT department,COUNT(*) FROM ' + @mainTable + 'GROUP BY department'; EXEC(@QUERY); -- runs okay! IF OBJECT_ID('tempdb..[##tmp5]') is not null BEGIN drop table [##tmp5] END SET @QUERY = ' SELECT studentid INTO [##tmp5] FROM ' + @mainTable + ' GROUP BY studentid having COUNT(*)=1; select * from [##tmp5];'; PRINT @QUERY; EXEC sp_executesql @QUERY; IF OBJECT_ID('tempdb..[#tmp3]') is not null BEGIN drop table [#tmp3] END SELECT S.department,COUNT(*) AS No INTO #TMP3 -- ONLY THIS SERVICE FROM servicesstats_0511_0412 s, #TMP5 T -- this is not being replaced yet by the @mainTable WHERE S.STUDENTID = T.STUDENTID GROUP BY S.department </code></pre> <p>Error : </p> <blockquote> <p><em>Invalid object name '#TMP5'.</em></p> </blockquote> <p>The problem is temporary table <code>#tmp5</code>, now if I were to run this it would work but it's not dynamic.</p> <pre><code>SELECT studentid INTO [#tmp5] FROM tableName GROUP BY studentid having COUNT(*)=1; </code></pre> <p>Basically I'm doing this because of the dynamic table name. But <code>#tmp</code> is throwing that error.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload