SQL Azure,截断并重新设置所有表

jos*_*hua 5 azure-sql-database

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
Run Code Online (Sandbox Code Playgroud)

所以我怎么用这个脚本做种子。

Ste*_*fan 4

这是我所做的:

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
Run Code Online (Sandbox Code Playgroud)