我想写一个动态删除若干个表的过程,要删除的表的名字在一个叫InstanceManagement表的字段中,请问这样的存储过程该怎么写?如何判断删除是否成功?
在写存储过程时,怎么用循环结构?

解决方案 »

  1.   

    declare @tb varchar(20)
    declare cur cursor for
    select col from InstanceManagement
    open cur
    fetch next from cur into @tb
    while @@fetch_status=0
    begin
    exec('drop table '+@tb)
    if @@error<>0 print 'fail:drop table '+@tb
    fetch next from cur into @tb
    end
    close cur
    deallocate cur
      

  2.   

    用游标,动态构造drop table 语句
      

  3.   

    请问这样的存储过程该怎么写?如何判断删除是否成功?
    在写存储过程时,怎么用循环结构?
    ----
    if exists(select 1 from sysobjects where id = object_id(@name) -- 是否存在
      exec('drop table '+ @name)
      

  4.   

    用游标从InstanceManagement表中取出数据,然后循环用动态SQL删除,类似如下:
    @TableName用来存放游标依次取出的要删除的表名.Declare @Sql nvarchar(1000)
    Set @Sql = 'Drop Table '+ @TableName
    Exec(@Sql)
      

  5.   

    我对“自强不息”的代码有一些疑问:
    1、在变量前面加两个@@是什么意思
    2、fetch next from cur into @tb 这行语句是干什么用的
    谢谢
      

  6.   

    declare @str varchar(8000)
    set @str = ''select @str = @str + ' drop table' tablename from InstanceManagement where tablename is not nullexec(@str)
    if @@error <> 0 print '删除失败'在SQL server中可以使用while循环
      

  7.   

    应该是
    select @str = @str + ' drop table' + [tablename] from [InstanceManagement] where [tablename] is not null
      

  8.   

    我在连续执行两遍存储过程的时候,第二遍总是提示游标已打开,可是我确实在存储过程中关闭了游标,这是为什么关闭游标之后,还要deallocate