DECLARE @tablename VARCHAR(30),
@sql VARCHAR(500)DECLARE cur_delete_table CURSOR READ_ONLY FORWARD_ONLY FORSELECT name FROM sysobjects WHERE name LIKE 'PUB%' AND type='U'OPEN cur_delete_tableFETCH NEXT FROM cur_delete_table INTO @tablenameWHILE @@FETCH_STATUS = 0BEGINSELECT @sql='delete from '+@tablenameEXEC (@sql)FETCH NEXT FROM cur_delete_table INTO @tablenameENDCLOSE cur_delete_tableDEALLOCATE cur_delete_table
================================================
有时候我们需要清空数据库中所有用户表的数据,如果一张表一张表的清空的话,遇到一个庞大的数据系统估计得崩溃了. 用游标加上用变量来引用表名就可以做到这一点. 用变量来引用表名对表操作可以用在存储过程中,根据需要动太选择引用某个表的数据或对其操作
//定义游标 DECLARE tables_cursor CURSOR
FOR
SELECT name FROM sysobjects WHERE type = 'U' //选择用户表名
OPEN tables_cursor //打开游标连接
DECLARE @tablename sysname // 定义变量
FETCH NEXT FROM tables_cursor INTO @tablename //结果集中一行一行读取表名
WHILE (@@FETCH_STATUS <> -1) //判断游标状态
BEGIN
EXEC ('TRUNCATE TABLE ' + @tablename) //清空表中的数据
FETCH NEXT FROM tables_cursor INTO @tablename //下一行数据
END
DEALLOCATE tables_cursor //关闭游标
例如:
CREATE proc ClearAllUserTable
as begin DECLARE tables_cursor CURSOR FOR SELECT name FROM sysobjects WHERE type = 'U' OPEN tables_cursor DECLARE @tablename sysname FETCH NEXT FROM tables_cursor INTO @tablename WHILE (@@FETCH_STATUS <> -1) BEGIN --print @tablename EXEC ('TRUNCATE TABLE ' + @tablename) FETCH NEXT FROM tables_cursor INTO @tablename END DEALLOCATE tables_cursor end; GO======================================================================
SQLSERVER批量删除数据库中的表,存储过程,触发器
MSSQL批量删除数据库中的表或者存储过程
先在系统表中找到要处理的表名或者是存储过程的名字,在用游标对其进行处理
注意 sysobjects.xtype的值不同 删除命令是不同的如删除存储过程用drop PROCEDURE PROCEDURENAME 删除表用 drop table tablename sysobjects.xtype的值表示的意思如下表:C:检查约束。 D:默认的约束 F:外键约束 L:日志 P:存储过程 PK:主键约束 RF:复制过滤存储过程 S:系统表格 TR:触发器 U:用于表格。 UQ:独特的约束。批量处理的代码如下:DECLARE cursorname cursor for select 'drop PROCEDURE '+name from sysobjects where name like 'xx%' and xtype = 'p' --删除对应的存储过程DECLARE cursorname cursor for select 'drop table '+name from sysobjects where name like 'xx%' and xtype = 'u' --删除对应的表open cursornamedeclare @curname sysnamefetch next from cursorname into @curnamewhile(@@fetch_status=0) begin exec(@curname)fetch next from cursorname into @curnameendclose cursornamedeallocate cursorname