Make SQL Server write its own scripts

Make SQL Server write your scripts for you!

Say you want to create a T-SQL script to backup every database on your SQL Server and there are over 100.

You can obtain a list of all your databases with the following command:

SELECT NAME FROM sys.databases

That lists all databases on that SQL server.  You can also add literal text in your query. This is a valid query:

SELECT 'Do not forget to back up database ', NAME FROM sys.databases

That gives you two columns, but you could also make it one column with a + instead of a comma
SELECT 'Do not forget to back up database ' + NAME FROM sys.databases

I went a step further and got this select statement to generate my backup statements
SELECT 'BACKUP DATABASE ' + NAME + ' TO DISK = ''C:\' + NAME + '.BAK'' FROM sys.databases

Note: Those are all single quotes above. Two single quotes are used to place a single quote (escape character).

The output looks like:
BACKUP DATABASE WSS_Content_DB1 TO DISK = 'C:\WSS_Content_DB1.BAK'

Only for all your databases.  Just copy the output into the query window or save it as a script and you're done.
 

Comments

Popular posts from this blog

Security Considerations When Using SharePoint Online

Setting SharePoint announcements to auto delete after expiration

Unexpected Integers where dates should be with Excel Online (Business) connector in SharePoint Online