日期:2014-05-18  浏览次数:20483 次

bcp工具运行的存储过程含有临时表,函数时出现无效对象的错误
--此存储过程含有临时表
create       proc       test      
as      
select       id,name    
into   #tmp
from       sysobjects      
select   *
from   #tmp
drop   table   #tmp
go      
-----在查询分析器中运行没问题
exec           pubs..test
go
-----   用BCP就会出现错误   '#tmp '对象无效
    declare       @s       varchar(8000)      
    set       @s= 'bcp       "exec           pubs..test "       queryout       "c:\ '+convert(varchar,getdate(),112)+ '.csv "   -T       /c '      
    exec       master..xp_cmdshell       @s      
    go      
       
    drop       proc       test

如果不能这么用有什么好的解决办法啊?


------解决方案--------------------
--先把exec test的结果存储辅助表t
create table t(id int,name varchar(1000))
insert t exec test

--用BCP
declare @s varchar(8000)
set @s= 'bcp "select * from pubs..t " queryout "c:\ '+convert(varchar,getdate(),112)+ '.csv " -T /c '
exec master..xp_cmdshell @s
go

drop proc test
drop table t

------解决方案--------------------
楼主,存储过程的临时表,存储过程执行完毕就自动删除了,最后那句drop没有必要了