azure-sql-database - Sql Azure , 截断和重新设定所有表

标签 azure-sql-database

DBCCSql 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

关于azure-sql-database - Sql Azure , 截断和重新设定所有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21520897/

相关文章:

azure-sql-database - 如何在 azure sql 中创建包含的数据库和用户

Azure ARM 模板 - 嵌套资源引用

database - 整个本地数据库与 sql azure 同步

azure - Azure 数据库的密码重置

sql-server - 使用 Azure SQL 的 Azure 自动故障转移组中的问题

azure - 我的 Azure 项目设置的数据传输费用是多少

sql-server - 对 Azure SQL 数据库表进行更改时调用外部 API

Azure Redis 缓存作为数据存储?

sql-server - 如何在 ETL 管道中正确截断临时表?

Azure数据工厂: How to rename blob csv or text file in blob storage during copy or import?