Possible Duplicate:
TSQL Writing into a Temporary Table from Dynamic SQL
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
Error :
Invalid object name ‘#TMP5’.
The problem is temporary table #tmp5, now if I were to run this it would work but it’s not dynamic.
SELECT studentid
INTO [#tmp5]
FROM tableName
GROUP BY studentid
having COUNT(*)=1;
Basically I’m doing this because of the dynamic table name. But #tmp is throwing that error.
You are using a local temporary table, which only exists within the scope of your dynamic sql, so you could reference it as follows without error:
However, when you try and access it outside of the scope of your dynamic sql you can no more access it that you could from another window in SSMS. You’ll need to use a global temporary table, then you can access it:
Just be aware of possible issues in a multi user environment.