Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

MSSQL Table Backup Script

Posted on August 20, 2015October 26, 2015 By David Kittell

This is a quick way to backup table structure and data, this will go out to the system table and query all tables then provide a script to recreate the tables.

SELECT 'create table [' + so.NAME + '] (' + o.list + ')' + CASE
		WHEN tc.Constraint_Name IS NULL
			THEN ''
		ELSE 'ALTER TABLE ' + so.NAME + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List) - 1) + ')'
		END
FROM sysobjects so
CROSS APPLY (
	SELECT '  [' + column_name + '] ' + data_type + CASE data_type
			WHEN 'sql_variant'
				THEN ''
			WHEN 'text'
				THEN ''
			WHEN 'ntext'
				THEN ''
			WHEN 'xml'
				THEN ''
			WHEN 'decimal'
				THEN '(' + cast(numeric_precision AS VARCHAR) + ', ' + cast(numeric_scale AS VARCHAR) + ')'
			ELSE coalesce('(' + CASE
						WHEN character_maximum_length = - 1
							THEN 'MAX'
						ELSE cast(character_maximum_length AS VARCHAR)
						END + ')', '')
			END + ' ' + CASE
			WHEN EXISTS (
					SELECT id
					FROM syscolumns
					WHERE object_name(id) = so.NAME
						AND NAME = column_name
						AND columnproperty(id, NAME, 'IsIdentity') = 1
					)
				THEN 'IDENTITY(' + cast(ident_seed(so.NAME) AS VARCHAR) + ',' + cast(ident_incr(so.NAME) AS VARCHAR) + ')'
			ELSE ''
			END + ' ' + (
			CASE
				WHEN IS_NULLABLE = 'No'
					THEN 'NOT '
				ELSE ''
				END
			) + 'NULL ' + CASE
			WHEN information_schema.columns.COLUMN_DEFAULT IS NOT NULL
				THEN 'DEFAULT ' + information_schema.columns.COLUMN_DEFAULT
			ELSE ''
			END + ', '
	FROM information_schema.columns
	WHERE table_name = so.NAME
	ORDER BY ordinal_position
	FOR XML PATH('')
	) o(list)
LEFT JOIN information_schema.table_constraints tc ON tc.Table_name = so.NAME
	AND tc.Constraint_Type = 'PRIMARY KEY'
CROSS APPLY (
	SELECT '[' + Column_Name + '], '
	FROM information_schema.key_column_usage kcu
	WHERE kcu.Constraint_Name = tc.Constraint_Name
	ORDER BY ORDINAL_POSITION
	FOR XML PATH('')
	) j(list)
WHERE xtype = 'U'
	AND NAME NOT IN ('dtproperties')
ORDER BY so.NAME

This is a bit of a hack but works to backup all the rows in your tables. Run the query and it will generate the proper syntax to run the bcp Utility.

SET NOCOUNT ON

DECLARE @AllTables TABLE (
	DBName NVARCHAR(200)
	,SchemaName NVARCHAR(200)
	,TableName NVARCHAR(200)
	)
DECLARE @SearchDB NVARCHAR(200)
	,@SearchS NVARCHAR(200)
	,@SearchTbl NVARCHAR(200)
	,@SQL NVARCHAR(4000)

SET @SearchDB = NULL --Search for DB, NULL for all Databases
SET @SearchS = NULL --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL --Search for Tables, NULL for all Tables
SET @SQL = 'SELECT
        ''?''
        ,s.name
        ,t.name
         FROM [?].sys.tables t
         JOIN sys.schemas s on t.schema_id=s.schema_id
         WHERE  ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
         AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
         AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
      -- AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
           '

-- Remove the '--' from the last statement in the WHERE clause to exclude system tables
INSERT INTO @AllTables (
	DBName
	,SchemaName
	,TableName
	)
EXEC sp_MSforeachdb @SQL

SET NOCOUNT OFF

SELECT 'Backup' AS [Action]
	,('bcp.exe "select * from [' + DBName + '].[' + SchemaName + '].[' + TableName + ']" queryout "' + @@Servername + '_' + DBName + '_' + TableName + '.bcp" -N -S ' + @@Servername + ' -T -E') AS [Script]
FROM @AllTables
WHERE DBName NOT IN (
		'master'
		,'tempdb'
		,'msdb'
		,'ReportServer'
		,'ReportServerTempDB'
		)

SELECT 'Restore' AS [Action]
	,('bcp.exe [' + DBName + '].[' + SchemaName + '].[' + TableName + '] in "' + @@Servername + '_' + DBName + '_' + TableName + '.bcp" -N -S ' + @@Servername + ' -T -E') AS [Script]
FROM @AllTables
WHERE DBName NOT IN (
		'master'
		,'tempdb'
		,'msdb'
		,'ReportServer'
		,'ReportServerTempDB'
		)

Reference: http://stackoverflow.com/questions/21547/in-sql-server-how-do-i-generate-a-create-table-statement-for-a-given-table

Originally Posted on August 20, 2015
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code MSSQL MSSQL - Audit SQL

Post navigation

Previous post
Next post

Related Posts

C# – Start/Stop/Restart Services

Posted on December 14, 2013December 2, 2019

using System.ServiceProcess; The following method tries to start a service specified by a service name. Then it waits until the service is running or a timeout occurs. public static void StartService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); try { TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); }…

Read More

BASH – Web Ping Log

Posted on January 29, 2024August 17, 2024

Sometimes you need a simple log to know when a site is up or down. Create a script like below and then put it in your crontab. #!/bin/bash echo ‘Begin ping’ if ping -c 1 kittell.net &> /dev/null; then echo "$(date "+%Y-%m-%d %H.%M.%S") – Success" >> /var/log/web_ping.log else echo "$(date…

Read More

PHP – WordPress – Blog Info

Posted on February 16, 2016

This is a simple piece of code to provide basic information about your blog. The first lines of the code will restrict the PHP access to the command line interface (CLI) so not just anyone could/should be able to see the details. Additional Mime Types can be seen at: http://codex.wordpress.org/Function_Reference/get_allowed_mime_types…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • Open On Screen Keyboard (OSK)
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes