/* Script to set database to single user mode and close all user connections
Note that this command will kill all user connections used the RollBack After
command to wait for users to log out.
*/
Use Master
go
Alter Database WriteDatabaseNameHere
Set Single_User With Rollback Immediate
go
---Now let said you want to rename the db
Alter database WriteDatabaseNameHere modify Name = WriteNewDatabaseNameHere
go
--Finally set database back to multi_user mode
Alter Database WriteDatabasenameHere
set Multi_user
go
USE DATABASENAME
select
tb.name as TableName
,max (p.rows) as RecordCount
from sys.tables tb
inner join sys.indexes i
on tb.object_id = i.object_id
and tb.type = 'U'
inner join sys.partitions p
on p.object_id = i.object_id
and p.index_id= i.index_id
group by tb.name
order by RecordCount
go
--------------4. Restore Relationships. ON delete NO action to be
research ------------
/* Restore relationships for delete set to no action; for update
set to no action as on
original reverse eng. model
*/
declare @ChildTable varchar (max) -- Child table Name
declare @ChildColumn varchar(max)-- Child column Name
declare @MasterTable varchar (max) -- Master TAble
declare @MasterColumn varchar (max) -- Master Column reference
declare @sqlcmd varchar (max) -- Sql Command
declare @ConstraintName varchar(max) -- Constraint Name
declare ADD_Constraint cursor
fast_forward for
select distinct ConstraintName,ChildTable,ChildColumn,MasterTable,MasterColumn
from [CoDE].[dbo].t_FK_Xref order
by ConstraintName
open ADD_Constraint
fetch next from ADD_Constraint
into @ConstraintName,
@ChildTable,
@ChildColumn,
@MasterTable,
@MasterColumn
while @@Fetch_Status = 0
begin
begin try
select @sqlcmd = 'alter
table '+@ChildTable+' with nocheck add constraint '+@ConstraintName+' foreign key '+'('+@ChildColumn+')'+' references '+@MasterTable+' ('+@MasterColumn+')'+' on delete no action on update no action'
exec (@sqlcmd)
fetch next from ADD_Constraint
into @ConstraintName,
@ChildTable,
@ChildColumn,
@MasterTable,
@MasterColumn
end try
begin catch
print @sqlcmd+'
***** Error checkpoint '
fetch next from ADD_Constraint
into @ConstraintName,
@ChildTable,
@ChildColumn,
@MasterTable,
@MasterColumn
end catch
end
close ADD_Constraint
Deallocate ADD_Constraint
go
---------------5. Restore CHECK Constraints---------------
-- Now enable referential integrity again
--EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
print 'Constraints Restored'
No comments:
Post a Comment