I am writing a maintenance plan where databases will be detached then the content of the folder it resided in will be moved to another drive for archiving.
declare @db varchar(500), @path varchar(max), @SQL varchar(max)
declare u_cur cursor fast_forward for
select name, [filename] from #DbsToBeDetached
open u_cur
fetch next from u_cur into @db, @path
while (@@FETCH_STATUS = 0)
begin
SET @SQL = 'ALTER DATABASE ' + @db + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE;'
EXEC(@SQL)
EXEC sp_detach_db @db, 'true';
set @path = MagicFunction(@path)
exec sp_xp_cmdshell 'move /Y "' + @path + '" "e:\archive\"' + @db + '"'
fetch next from u_cur into @db, @path
end
close u_cur
deallocate u_cur
The only thing I am stuck on is what do I do where it says MagicFunction to turn a path like
D:\data\conversions\wi_sql2005\30950 example database\30950_data.mdf
to
D:\data\conversions\wi_sql2005\30950 example database
You could create a function using the following logic (or just use the SQL inline):