I'm trying to back up all the tables in a SQL Server Database. Here's the logic I'd like to execute:
For Each TableName in MyDatabase
SELECT *
FROM TableName
Export Results to C:\TableName.csv
Loop
I'm trying to back up all the tables in a SQL Server Database. Here's the logic I'd like to execute:
For Each TableName in MyDatabase
SELECT *
FROM TableName
Export Results to C:\TableName.csv
Loop
*Disclaimer that none of these will ever be a better option than a native backup in terms of backing of data. I'm assuming you simply want some flat file backups.
Several manual options are available from generating the scripts and data via Tasks->Generate Scripts
, to manually running a select * from tablename
and then right clicking ->
Copy including header columns into their own excel files.
More automated options involve SSIS packages to handle this sort of enumerator logic. I believe that the best way to handle this would be a powershell script. Please see @Smor's comment to the following answer: SQL Server Management Studio 2012 - Export all tables of database as csv , for a detailed powershell solution.
The only T-SQL based querying options I'm aware of would be to attempt something of the following:
SELECT
'insert into OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',
''Excel 8.0;Database=@filepath\'' + t.name + '.csv '', --@filepath would be replaced with your logic for determining filename+path
''SELECT * FROM [SheetName$]'')
select * from ' + t.name + ';'
FROM
sys.tables
And executing the results of this script.