存储过程里的临时表无效
我创建了一个存储过程,存储过程里用SELEC…into创建两个临时表,然后查询临时表里的数据,报第二个临时表无效
CREATE PROCEDURE HarmoniousData(@str nvarchar(2000),@number int) AS
declare @sql nvarchar(4000)
--插入合作企业信息到临时表 #tempEnterprise
if object_id('#tempEnterprise') is not null
drop table #tempEnterprise
SELECT DISTINCT CheckName, CheckApprovalNo, CheckEnterprise, typename into #tempEnterprise
FROM T_Enterprise a,(select typeid,typename from t_type where themeid=2)b
WHERE (EnterpriseId IN
(SELECT id
FROM T_ContractEnterprise
WHERE (IDType = 1) AND ([PERCENT] = 100) AND isstop = 0 ))
and a.typeid=b.typeid
exec(' if object_id(''#tempEnterpriseResult'') is not null
drop table #tempEnterpriseResult
select a.reportid,a.checkname,a.playdate,a.checkapprovalno,a.checkenterprise,a.typename,a.channelno into #tempEnterpriseResult
from t_result a,#tempEnterprise b
where '+@str+'
and a.checkname=b.checkname and a.checkapprovalno=b.checkapprovalno and a.checkenterprise=b.checkenterprise and a.typename=b.typename')
exec('SELECT * FROM T_Result a,#tempEnterprise b
WHERE '+@str+'
and a.checkname=b.checkname and a.checkapprovalno=b.checkapprovalno and a.checkenterprise=b.checkenterprise and a.typename=b.typename
and reportid not in (select reportid from #tempEnterpriseResult a where
(select count(1) from #tempEnterpriseResult pp where --a.reportid=pp.reportid and
a.checkname=pp.checkname and a.playdate=pp.playdate and a.checkapprovalno=pp.checkapprovalno and a.checkenterprise=pp.checkenterprise
and a.typename=pp.typename
and a.channelno>pp.channelno)<'+@number+')')
GO
[解决办法]
exec开启了另外一个会话,你的局部临时表已经失效,所以考虑一下用全局临时表或者实体表,但是这个在并发下容易出现冲突。
[解决办法]
第2个临时表#tempEnterpriseResult'是在动态语句里面创建的.当动态语句执行完了,他也就销毁了.
如果,你必须要在动态语句里面调用临时表,请你先在外面的非动态语句中去创建好临时表,然后再调用即可 .
[解决办法]