Poniżej przedstawiam skrypt, który generuje kod do odłączenia (detach) wszystkich baz danych użytkownika.
SET NOCOUNT ON
DECLARE @dbname as varchar(80)
PRINT '--SERVER NAME : ' + upper(@@servername) + '--> Begin script databases'
PRINT '----------------------------------------------'
PRINT ''
PRINT ''
DECLARE DatabaseNameList_cur CURSOR STATIC LOCAL FORWARD_ONLY
FOR
SELECT RTRIM(LTRIM([name]))
FROM sys.databases
WHERE database_id > 4 -- only users databases
AND STATE_DESC='ONLINE';
OPEN DatabaseNameList_cur
FETCH NEXT FROM DatabaseNameList_cur into @dbname
IF @@FETCH_STATUS <> 0
PRINT 'No database to backup...Please check your script!!!'
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'sp_detach_db ' + @dbname
PRINT 'go'
PRINT 'print ''Detach of ' + upper(@dbname) + ' database successfully completed'''
PRINT 'go'
PRINT ' '
FETCH NEXT FROM DatabaseNameList_cur INTO @dbname
END
CLOSE DatabaseNameList_cur
DEALLOCATE DatabaseNameList_cur
PRINT '----------------------------------------------'
PRINT ''
PRINT ''
PRINT 'print ''SERVER NAME : ' + upper(@@servername) + '--> All databases successfully detached'''