azure-sql-database – Sql Azure,截断并重新设置所有表

DBCC在Sql Azure中不可用,所以基本上我们无法执行DBCC操作.那么我们如何在Sql Azure中重置身份.

我写这个来截断所有记录并将表重新设置为1,显然这不起作用,因为DBCC不被允许.

EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
EXEC sp_MSForEachTable ‘DELETE FROM ?’
EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’
DBCC checkident (?, RESEED, 1)  ??
GO

那我怎么用这个脚本做Reseed.

最佳答案 这是我做的:

declare @dropConstraintsSql nvarchar(max);
declare @enableConstraintsSql nvarchar(max);
declare @deleteSql nvarchar(max);

-- create a string that contains all sql statements to drop contstraints 
-- the tables are selected by matching their schema_id and type ('U' is table)   

SELECT @dropConstraintsSql = COALESCE(@dropConstraintsSql + ';','') + 'ALTER TABLE [' + name + '] NOCHECK CONSTRAINT all'
FROM sys.all_objects 
WHERE type='U' and schema_id=1
-- AND... other conditions to match your tables 


-- create a string that contains all your DELETE statements...

SELECT @deleteSql = COALESCE(@deleteSql + ';','') + 'DELETE FROM [' + name + '] WHERE ...'
FROM sys.all_objects 
WHERE type='U' and schema_id=1
-- AND ... other conditions to match your tables 

-- create a string that contains all sql statements to reenable contstraints    

SELECT @enableConstraintsSql = COALESCE(@enableConstraintsSql + ';','') + 'ALTER TABLE [' + name + '] WITH CHECK CHECK CONSTRAINT all'
FROM sys.all_objects 
WHERE type='U' and schema_id=1
-- AND ... other conditions to match your tables 

-- in order to check if the sqls are correct you can ...
-- print @dropConstraintsSql
-- print @deleteSql
-- print @enableConstraintsSql


-- execute the sql statements in a transaction

begin tran 

exec sp_executesql  @dropConstraintsSql
exec sp_executesql  @deleteSql
exec sp_executesql  @enableConstraintsSql

-- commit if everything is fine
rollback
点赞