In the next sample, I'm demonstrate, how to generate script, that backup all the Dbs in the server.
After script execution , you will get the required script and you can check it before running the script
CREATE TABLE #t(dbName nvarchar(100))
DECLARE @command varchar(max)
SELECT @command = 'USE ?
begin try
if DB_ID()>4 --here you can place more selective conditions
begin
INSERT INTO #t
SELECT DB_Name()
end
end try
begin catch
select Db_name() , error_message()
end catch
'
--print @command
EXEC sp_MSforeachdb @command
DECLARE @DbName VARCHAR(10)
DECLARE Db_Cursor CURSOR
FOR SELECT dbName FROM #t
ORDER BY dbName
OPEN Db_Cursor
FETCH NEXT FROM Db_Cursor INTO @DbName
WHILE @@FETCH_STATUS = 0
BEGIN
print 'USE '+@DbName
print ' Go'
print'BACKUP DATABASE '+@DbName+' TO DISK = N''D:\'+@DbName+'.bak'' WITH NOFORMAT, NOINIT,
NAME = N'''+@DbName+'-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
'
FETCH NEXT FROM Db_Cursor INTO @DbName
END
Close Db_Cursor
DEALLOCATE Db_Cursor
SELECT dbName FROM #t
ORDER BY dbName
DROP TABLE #t