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
错误:
无效的对象名称'#TMP5'。
问题是临时表#tmp5
,现在如果我要运行它,它会起作用,但它不是动态的。
SELECT studentid
INTO [#tmp5]
FROM tableName
GROUP BY studentid
having COUNT(*)=1;
基本上我是因为动态表名而这样做的。但是#tmp
正在抛出这个错误。
答案 0 :(得分:2)
您正在使用本地临时表,该表仅存在于动态sql的范围内,因此您可以按如下方式引用它而不会出现错误:
SET @QUERY = ' SELECT studentid
INTO [#tmp5]
FROM ' + @mainTable + '
GROUP BY studentid
having COUNT(*)=1;
SELECT *
FROM [#tmp]';
EXEC sp_executesql @QUERY;
但是,当您尝试在动态sql范围之外访问它时,您无法再从SSMS中的另一个窗口访问它。您需要使用全局临时表,然后才能访问它:
SET @QUERY = ' SELECT studentid
INTO [##tmp5]
FROM ' + @mainTable + '
GROUP BY studentid
having COUNT(*)=1;';
EXEC sp_executesql @QUERY;
SELECT *
FROM [##Tmp5];
请注意多用户环境中可能存在的问题。