2016-08-05 89 views
1

我有这个代码,应该删除一个临时表,如果它存在,但我仍然收到错误:Cannot drop the table '#jobsconsumed', because it does not exist or you do not have permission.有人可以帮我吗?我的I.T.管理员不认为这是一个权限问题。#temp表没有被丢弃

IF (SELECT object_id('TempDB.#jobsconsumed')) IS NULL 
    BEGIN 
    DROP Table #jobsconsumed 
END 
+1

我想你应该尝试两点:'TempDB的..#jobsconsumed' – HoneyBadger

+0

什么是2点呢? – whatwhatwhat

+1

可能'不是NULL'是你真正想要的逻辑。为什么要删除不存在的内容? –

回答

3
IF (SELECT object_id('TempDB.#jobsconsumed')) IS NULL 
    BEGIN 
    DROP Table #jobsconsumed 
END 

上面的代码将进入开始条款,只有当不是Temptable存在..

检查和下降不是Temptable,正确的方法是低于

IF object_id('Tempdb..#test') is Not null 
is same as 
    IF object_id('Tempdb.dbo.#test') is Not null 
Drop Table #test 

有没有必要在这种情况下,由于IF将执行立即声明

s对临时表的架构方面OME测试..

use tempdb; 

create schema hr 

create table hr.#t(c int) --this will work 
create table #t(c int) --this will fail 

create table #t1 --no schema ,so it will create a temp table in DBO Schema by default. 

--To drop the table 
drop table #t --this will drop across all schemas 
+0

问题:我正在使用这一行将值放入#temp表中。 '(SELECT t.ref_num,t.ref_line_suf INTO #jobsconsumed FROM ISW_LPTrans AS t WHERE t.item = @item AND t.lot = @lot AND(t.trans_type ='I'or t.trans_type ='W')) '但根据你的回答,这应该失败,因为我使用'#jobsconsumed'而不是'dbo。#jobsconsumed'。为什么它没有失败? – whatwhatwhat

+1

它不会失败,bcoz默认会在dbo.schema中创建 – TheGameiswar