国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

保存數據庫中其他對象不變,刪除數據庫中所有數據的實現方法

2024-07-21 02:07:58
字體:
來源:轉載
供稿:網友


原帖內容:
怎樣把數據庫中所有數據刪除,然后把所有的自動增量復位?
表太多,無法手工完成。
http://community.csdn.net/expert/topic/3094/3094555.xml?temp=.2920954

/*
--原本打算這樣
--先禁用所有外鍵約束
exec sp_msforeachtable "alter table ? nocheck constraint all"
--然后刪除數據
exec sp_msforeachtable "truncate table ?"
--再啟用所有外鍵約束
exec sp_msforeachtable "alter table ? check constraint all"
--但是禁用了以后,truncate table 不行,會提示沖突
*/

--現在我的想法是(語句待優化):


--第一部分,生成建立外鍵的語句保存到#tmp
declare @name varchar(200),@tmp1 varchar(500),@tmp2 varchar(500)

create table #tmp
(
string varchar(8000)
)

select  表名稱=object_name(b.fkeyid)
 ,外鍵名稱=a.name
 ,引用的列名=(select name from syscolumns where colid=b.fkey and id=b.fkeyid)
 ,引用的表名=object_name(b.rkeyid)
 ,已引用的列名=(select name from syscolumns where colid=b.rkey and id=b.rkeyid)
into #t from sysobjects a
 join sysforeignkeys b on a.id=b.constid
 join sysobjects c on a.parent_obj=c.id
where a.xtype='f' and c.xtype='u'

declare cur_test cursor for
 select a.name from sysobjects a join sysobjects c on a.parent_obj=c.id where a.xtype='f' and c.xtype='u'
open cur_test
fetch next from cur_test into @name
while (@@fetch_status <> -1)
begin
 if (@@fetch_status <> -2)
 begin
  select @tmp1='',@tmp2=''
  select @[email protected]+'['+引用的列名+'],',@[email protected]+'['+已引用的列名+'],' from #t where 外鍵名稱[email protected]
  insert into #tmp select top 1 'alter table [dbo].['+表名稱+'] add constraint ['[email protected]+'] foreign key ( '+left(@tmp1,len(@tmp1)-1)+' ) references ['+引用的表名+'] ( '+left(@tmp2,len(@tmp2)-1)+' )' from #t where 外鍵名稱[email protected]
 end
 fetch next from cur_test into @name
end

close cur_test
deallocate cur_test
drop table #t

--第二部分,刪除所有外鍵
declare @string varchar(8000)
while exists(select name from sysobjects where type='f')
begin
 select @string='alter table '+b.name+' drop constraint '+a.name+char(13)
  from (select parent_obj,name from sysobjects where type='f') a,
        (select id,name from sysobjects where objectproperty(id, n'isusertable') = 1) b
    where a.parent_obj=b.id
 exec(@string)
end

--第三部分,刪除所有表的記錄,并且把identity復位
exec sp_msforeachtable "truncate table ?"

--第4部分,執行#tmp里面的建立外鍵的語句,恢復外鍵
declare cur_test2 cursor for select string from #tmp

open cur_test2
fetch next from cur_test2 into @string
while (@@fetch_status <> -1)
begin
 if (@@fetch_status <> -2)
 begin
  exec(@string)
  print @string
 end
 fetch next from cur_test2 into @string
end

close cur_test2
deallocate cur_test2

drop table #tmp

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 虎林市| 洛宁县| 沭阳县| 延寿县| 巨野县| 孝感市| 耿马| 五莲县| 巴南区| 湘潭市| 漾濞| 汉阴县| 西宁市| 南宁市| 岑溪市| 游戏| 宝应县| 丽江市| 衡南县| 万荣县| 阳西县| 枞阳县| 砚山县| 恭城| 太和县| 雷波县| 天气| 汾西县| 日喀则市| 茌平县| 潼南县| 名山县| 镇远县| 高陵县| 县级市| 云南省| 乾安县| 名山县| 府谷县| 铁力市| 古蔺县|