可能重复:
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
正在抛出那个错误。