在存储过程中创建临时表的问题

lixinwyh 2003-12-25 11:20:29
我在一个存储过程中需要创建临时表
@parameter --传进来的参数,int
if @parameter=1
create table #table1(id int,...)
else if @parameter=2
create table #table1(name1 char(10),...)

创建的时候显示#table1已经存在,如果不是临时表就没问题?这个如何解决?
...全文
63 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
perfwell 2003-12-25
  • 打赏
  • 举报
回复
用表变量行的
@parameter --传进来的参数,int
if @parameter=1
DECLARE @table1(id int,...)
else if @parameter=2
 DECLARE @table1(name1 char(10),...)
zjcxc 2003-12-25
  • 打赏
  • 举报
回复
--用全局的临时表可以解决:

if @parameter=1
exec('create table ##table1(id int,...)'
else if @parameter=2
exec('create table ##table1(name1 char(10),...)'
zjcxc 2003-12-25
  • 打赏
  • 举报
回复
--这个是SQL存储过程检测上的缺陷.
realgz 2003-12-25
  • 打赏
  • 举报
回复
那你换成 exec ('create table #table1(name1 char(10),...)')
。。。哈哈。
lixinwyh 2003-12-25
  • 打赏
  • 举报
回复
另外不能使用游标,必须是临时表,因为还有别的用,会在存储过程之外使用
lixinwyh 2003-12-25
  • 打赏
  • 举报
回复
if @parameter=1
begin
if object_id(tempdb..#table1) is not null
drop table #table1
create table #table1(id int,...)
end
else if @parameter=2
if object_id(tempdb..#table1) is not null
drop table #table1

create table #table1(name1 char(10),...)
显示同样的错误,创建的时候显示#table1已经存在
我问的不是删除临时表,是这个错误如何解决
lixinwyh 2003-12-25
  • 打赏
  • 举报
回复
楼上说的都不行,我已经试过了
if @parameter=1
begin
if object_id(tempdb..#table1)
drop table #table1
create table #table1(id int,...)
end
else if @parameter=2
if object_id(tempdb..#table1)
drop table #table1

create table #table1(name1 char(10),...)

显示同样的错误,创建的时候显示#table1已经存在
sdhdy 2003-12-25
  • 打赏
  • 举报
回复
--用以下语句可判断,临时表是否存在,如果存在则drop掉,否则则创建
if exists(select 1 from tempdb..sysobjects where name like '#table1%' and xtype='u' )
drop table #table1
else
create table #table1(id int,...)
sdhdy 2003-12-25
  • 打赏
  • 举报
回复
@parameter --传进来的参数,int
if @parameter=1
begin
if exists(select 1 from tempdb..sysobjects where name like '#table1%' and xtype='u' )
drop table #table1
else
create table #table1(id int,...)
end
else
.....


perfwell 2003-12-25
  • 打赏
  • 举报
回复
马可,,,要看清题目,,,是在存储过程内部报错。。。
wuyanfeng 2003-12-25
  • 打赏
  • 举报
回复
第一种方法:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BBSA]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[BBSA]///(这是删表的语句,只能参考!)
第二种方法:
@parameter --传进来的参数,int
if @parameter=1
DECLARE @table1(id int,...)
else if @parameter=2
 DECLARE @table1(name1 char(10),...)
txlicenhe 2003-12-25
  • 打赏
  • 举报
回复
先在存储过程的外面运行 drop table #table1

或打开另一个窗口创建该存储过程即可。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧