2

可能重复:
TSQL 从动态 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

错误 :

无效的对象名称“#TMP5”。

问题是临时表#tmp5,现在如果我要运行它,它会工作,但它不是动态的。

SELECT studentid
INTO [#tmp5]
FROM tableName
GROUP BY studentid
having COUNT(*)=1;

基本上我这样做是因为动态表名。但是#tmp正在抛出那个错误。

4

1 回答 1

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];

请注意多用户环境中可能出现的问题。

于 2012-10-29T17:32:05.037 回答