作者:mobiledu2502897207 | 来源:互联网 | 2023-09-04 00:22
我创建了一个存储过程,存储过程里用SELEC…into创建两个临时表,然后查询临时表里的数据,报第二个临时表无效CREATEPROCEDUREHarmoniousData(@strnva
我创建了一个存储过程,存储过程里用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
22 个解决方案
(所影响的行数为 16 行)
(所影响的行数为 1159 行)
服务器: 消息 208,级别 16,状态 1,行 1
对象名 '#tempEnterpriseResult' 无效。
服务器: 消息 208,级别 16,状态 1,行 1
对象名 '#tempEnterpriseResult' 无效。
exec开启了另外一个会话,你的局部临时表已经失效,所以考虑一下用全局临时表或者实体表,但是这个在并发下容易出现冲突。
可是我有一个存储过程是先建了两个临时表,用exec分别向两个临时表时插数,然后再查询怎么可以呢?
如果你的返回结果列是固定的,那么使用我4楼的方式来实现,而不要用SELECT INTO
第2个临时表#tempEnterpriseResult'是在动态语句里面创建的.当动态语句执行完了,他也就销毁了.
如果,你必须要在动态语句里面调用临时表,请你先在外面的非动态语句中去创建好临时表,然后再调用即可 .
#tempEnterpriseResult a 不使用临时表的别名 试试
我现在直接把语句写在程序里了,可是我还是想知道在存储过程里怎么实现?高手们,快来给分析一下啊
#tempEnterpriseResult
这个临时表
在exec结束就销毁了吧
只要在同一个transaction里,local temp table不会因为exec的执行而失效,也不会另外开启新的session。
我帮你分析了一下你的执行逻辑。
报对象名 '#tempEnterpriseResult' 无效。错误是因为你在上面生成那个#tempEnterpriseResult 的地方(,“ into #tempEnterpriseResult”)并没有成功生成 ,原因很可能就是。。。。from t_result a,#tempEnterprise b。。。。返回的结果集为空,你仔细CHECK一下吧。
动态创建的临时表生命周期只限于动态执行。你可以先创建临时表,因为你的列是固定的,所以
create table #tb (col1 int)
exec('insert into #tb select col1 from tb where'+@str)
select * from #tb
drop table #tb