如何清空所有数据库中所有表里的所有数据?


用游标删除,写个列子,aaaa为定义的游标,在要删除的数据库中执行就会清空所有表

declare aaaa cursor

for select * from sysobjects where type = 'u'

declare @tbname varchar (100)

open aaaa

FETCH NEXT FROM AAAA INTO @TBNAME 

WHILE (FETCH_STATUS <> -1)

BEGIN 

    EXEC([email=]'DELETE'+@TBNAME[/email])

     

    FETCH NEXT FROM AAAA INTO @name

END

CLOSE AAAA

DEALLOCATE AAAA 









第二个方法









if exists (select * from sysobjects where type='P' and name=N'P_DeleteAllData' )

    drop procedure P_DeleteAllData

go



CREATE PROCEDURE P_DeleteAllData

as

    EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' --禁用约束

    EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL' --禁用触发器

    EXEC sp_MSForEachTable 'DELETE FROM ?' --删除所有表中的数据

    EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' --启用约束

    EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL' --启用触发器

go



--执行存储过程

--exec P_DeleteAllData --执行

你可能感兴趣的:(数据库)