Home  >  Article  >  Database  >  sql批量删除数据与批量删除数据库表语句

sql批量删除数据与批量删除数据库表语句

WBOY
WBOYOriginal
2016-06-07 17:49:112356browse

我们介绍了二种批量删除数据的方法(游标形式和sql存储过程),同时还介绍了批量删除数据库表的方法,有需要的同学可参考一下。

游标删除方法

 代码如下 复制代码

//定义游标

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 ('TRUNECATE TABLE ' + @tablename) //清空表中的数据

FETCH NEXT FROM tables_cursor INTO @tablename //下一行数据

END

 

DEALLOCATE tables_cursor //关闭游标

/42850.htm target=_blank >sql存储过程实例地

 代码如下 复制代码

Create PROCEDURE Batch_Delete
@TableName nvarchar(100), --表名
@FieldName nvarchar(100), --删除字段名
@DelCharIndexID nvarchar(1000)
as
DECLARE @PointerPrev int
DECLARE @PointerCurr int
DECLARE @TId NVARCHAR(50), @sql NVARCHAR(1000)

Set @PointerPrev = 1
while (@PointerPrev Begin
Set @PointerCurr = CharIndex(',',@DelCharIndexID,@PointerPrev)
if(@PointerCurr>0)
Begin
SET @TId = cast(SUBSTRING(@DelCharIndexID, @PointerPrev, @PointerCurr - @PointerPrev) As NVARCHAR(50))
SET @sql = 'Delete From '+ @TableName +' Where '+ @FieldName + ' = '''+ @TID+''''
Exec(@Sql)
Print('======='+@TId+'=======sql'+@Sql)
SET @PointerPrev = @PointerCurr + 1
Print(@PointerPrev)
End
else
Begin
Print('break')
Break
End
End
--删除最后一个,因为最后一个后面没有逗号,所以在循环中跳出,需另外再删除
SET @TId = cast(SUBSTRING(@DelCharIndexID, @PointerPrev, LEN(@DelCharIndexID) - @PointerPrev + 1) As NVARCHAR(50))
SET @sql = 'Delete From '+ @TableName +' Where '+ @FieldName + ' = '''+ @TID+''''
Exec(@Sql)
Print('======='+@TId+'=======sql'+@Sql)
GO

网上找的批量删除表方法

 代码如下 复制代码

  /*--------------------------------

功能说明:  批量DropTable

使用说明:  使用时一定要小心,因为删选表的where条件是like所有必须保证where

后的like确定与你要删除表名相匹配

---------------------------------*/

--------参数定义-------------------

DECLARE @tableName AS Nvarchar(50) --查询表名条件(小心!,确保like条件是你要Drop的表.TableName尽量精确)

SET @tableName='test' 

--------------------------------------

--SELECT name FROM sys.tables   WHERE name LIKE '%'+@tableName+'%' --查询出要删除表的名称

IF @tableName='' SET @tableName='tableName'--初始化TableName为tableName,防止@tableName为空

DECLARE @tableNames AS Nvarchar(3000)

DECLARE @sql AS Nvarchar(3000)

SET @tableNames=

(SELECT ','+name FROM sys.tables   WHERE name LIKE '%'+@tableName+'%'  FOR XML PATH(''))

SET @tableNames= Stuff(@tableNames,1,1,'')

SET @sql='DROP TABLE '+@tableNames

EXEC(@sql)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn