Excel VBA - 用于删除临时表的exec脚本

时间:2012-03-12 00:47:44

标签: sql-server-2008 excel-vba sql-drop vba excel

我想在运行宏时删除#temp表,使用是否正确:

tempdb..sysobjects

脚本是:

sScript = sScript + "IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE xtype = 'U' AND name like '#vl_enrolledByDate%') " & vbCrLf
sScript = sScript + "BEGIN " & vbCrLf
sScript = sScript + "DROP TABLE  #vl_enrolledByDate " & vbCrLf
sScript = sScript + "End " & vbCrLf

iVal = execute_sql_command(sServer, sDatabase, sScript)

sServer例如。是SQLPROD01和sDatabase例如。是scratchdb,但我读到#tables存储在tempdb数据库中,这就是表不存在的原因吗?

因此,当我运行宏时,它会返回以下错误消息:

Run-time error '-2147217865 (80040e37)':

Cannot drop the table '#vl_enrolledByDate', because it does not exist
in the system cataglog.

但是如果我创建一个非#表并且只使用

(SELECT * FROM sysobjects WHERE xtype = 'U' AND name like 'vl_enrolledByDate%')

没关系。

1 个答案:

答案 0 :(得分:0)

我总是有条件地删除这样的临时表:

if OBJECT_ID('tempdb..#temp') is not null
drop table #temp