Convert Microsoft Access to SQL Server - sql-server

I need to convert a Microsoft Access database (*.accdb) to SQL Server by command line in Linux.
Every time I run this task it should do:
Empty the database
Import the whole data from Microsoft Access database to SQL Server
My first idea was use mdb-tools to create a script.sql like this:
#!/bin/bash
MDB="$1"
DIALECT="sybase"
cat << EOF
-- Something to DROP all tables (not tested yet)
DECLARE #DropConstraints NVARCHAR(max) = ''
SELECT #DropConstraints += 'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)) + ' ' + 'DROP CONSTRAINT' + QUOTENAME(name)
FROM sys.foreign_keys
EXECUTE sp_executesql #DropConstraints;
GO
DECLARE #DropTables NVARCHAR(max) = ''
SELECT #DropTables += 'DROP ' + REPLACE(TABLE_TYPE, 'BASE ', '') + ' ' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES where TABLE_TYPE in ('BASE TABLE', 'VIEW')
EXECUTE sp_executesql #DropTables;
GO
EOF > script.sql
mdb-schema "$MDB" "$DIALECT" >> script.sql
TABLES=$(mdb-tables -1 "$MDB")
for table in $TABLES; do
mdb-export -D '%Y-%m-%d %H:%M:%S' -I "$DIALECT" "$MDB" $table >> script.sql
done
and then run script.sql in my SQL Server database with mssql-cli -S ***** -U ***** -U ***** -P ***** -d ***** -i script.sql
But it is to slow and I need something more direct.
I think I could do with bcp but I don't find any example.

Related

AWS RDS SQL Server : export large data to CSV file from stored procedure

Migrating from a hosted SQL Server to AWS RDS which is a managed service (SaaS), we couldn't enable xp_cmdshell.
Our java app currently use a stored procedure that use xp_cmdshell to execute BCP.exe (Bulk Copy Program is a command-line tool used to import or export data against a Microsoft SQL Server) to export large data to CSV files.
And as xp_cmdshell cannot be enabled on RDS, we cannot use it to execute BCP.
Stored procedure code:
declare #bcp_header varchar(8000)
declare #bcp varchar(8000)
declare #bcpCopy varchar(8000)
declare #deleteFile varchar(300)
select #bcp_header = 'BCP "' + #header_select + '" queryout ' + #pathAndFileName +'.csv -c -C 1252 -t; -T '
select #bcp = 'BCP "' + #sql_export + '" queryout '+ #pathAndFileName +'_data.csv -c -C 1252 -t; -T '
select #bcpCopy = 'TYPE '+ #pathAndFileName +'_data.csv >> '+ #pathAndFileName +'.csv'
select #deleteFile = 'DEL '+#pathAndFileName +'_data.csv'
exec master..xp_cmdshell #bcp_header
exec master..xp_cmdshell #bcp
exec master..xp_cmdshell #bcpCopy
exec master..xp_cmdshell #deleteFile
Can we use a T-SQL command to export the query result to a CSV file and host it on S3 ?
Can we use a T-SQL command to export the query result to a CSV file and host it on S3 ?
Nope. There are TSQL alternatives to the BCP command, but ONLY for IMPORT.
Your best bet is to write a program that returns the data from SQL via some sort of SELECT statement and writes out the file yourself - bascailly a homebrewn replacement to BCP.
There is nothing out of the box that can act as a BCP replacement as all non BCP bulk functionality is either for programmatic use OR import only.
The answer is use BCP.exe inside an SSIS package using the SQL Server that the SSIS instance uses.

SQL Server bcp utility does not create the txt file,

I'm new to this feature in SQL Server and could use some help. I'm experimenting with the BCP utility and the AdventureWorks2012 database.
I'm attempting to export data to a text file with the BCP utility and the code executes but a file is not created. Can you please look at my code and tell me where the problem(s) is/are.
I'm working out of a local copy of SQL Server Express. Thank you.
Declare #sql Varchar(8000)
Select #sql = 'bcp
+ SELECT FirstName, LastName
FROM AdventureWorks2012.Person.Person ORDER BY LastName, Firstname
+ queryout C:\Users\David\Desktop\yes.txt + -c -t, -T -S'
+ ##SERVERNAME
EXEC master..xp_cmdshell #sql
Here is my output when I run the query:
output
usage: bcp {dbtable | query} {in | out | queryout | format} datafile
[-m maxerrors] [-f formatfile] [-e errfile]
[-F firstrow] [-L lastrow] [-b batchsize]
[-n native type] [-c character type] [-w wide character type]
[-N keep non-text native] [-V file format version] [-q quoted identifier]
[-C code page specifier] [-t field terminator] [-r row terminator]
[-i inputfile] [-o outfile] [-a packetsize]
[-S server name] [-U username] [-P password]
[-T trusted connection] [-v version] [-R regional enable]
[-k keep null values] [-E keep identity values]
[-h "load hints"] [-x generate xml format file]
[-d database name] [-K application intent] [-l login timeout]
NULL
Here is the PRINT output:
bcp
+ "SELECT FirstName, LastName
FROM AdventureWorks2012.Person.Person ORDER BY LastName, Firstname"
+ queryout C:\Users\David\Desktop\yes.txt -c -t, -T -SHOMEPC\SQLINST01
TT's code worked. Here it is:
DECLARE #stmt_e VARCHAR(8000);
SET #stmt_e=
'BCP '+
'"SELECT FirstName,LastName FROM AdventureWorks2012.Person.Person ORDER BY LastName,Firstname" '+
'QUERYOUT "C:\Users\David\Desktop\yes.csv" '+
'-c -t, -T -S ' + ##SERVERNAME;
EXEC master.sys.xp_cmdshell #stmt_e;
The instructions for adding system permissions for database engine access can be found at the link below. I had to do this because my SQL Server Instance did not have permission to write to the path I was specifying.
https://msdn.microsoft.com/en-us/library/jj219062.aspx
The following snippet should run without problem on any SQL Server. It outputs all table information in INFORMATION_SCHEMA.TABLES as a comma separated file in C:\Temp\information_schema.csv.
Run this as a sanity check; it works without problem on my system, and it should on your system too. Run this from the AdventureWorks2012 database. If it doesn't work we'll have to delve deeper.
DECLARE #stmt_c VARCHAR(8000);
SET #stmt_c=
'BCP '+
'"SELECT*FROM '+QUOTENAME(DB_NAME())+'.INFORMATION_SCHEMA.TABLES" '+
'QUERYOUT "C:\Temp\information_schema.csv" '+
'-c -t, -T -S ' + ##SERVERNAME;
EXEC master.sys.xp_cmdshell #stmt_c;
Now if this works, adapt this to your query:
DECLARE #stmt_e VARCHAR(8000);
SET #stmt_e=
'BCP '+
'"SELECT FirstName,LastName FROM AdventureWorks2012.Person.Person ORDER BY LastName,Firstname" '+
'QUERYOUT "C:\Users\David\Desktop\yes.txt" '+
'-c -t, -T -S ' + ##SERVERNAME;
EXEC master.sys.xp_cmdshell #stmt_e;
This Should work
DECLARE #sql VARCHAR(8000);
SELECT #sql = 'bcp "SELECT FirstName, LastName FROM'+
' AdventureWorks2008.Person.Person ORDER BY FirstName, LastName" queryout'+
' C:\Users\David\Desktop\yes.txt -c -t, -r \r\n -S '+##servername+' -T';
EXEC master..xp_cmdshell #sql;
Should warpped the query in double quotes. I have removed an extra + before the -c.
You can test out the BCP on command prompt first. make sure it is working before using xp_cmdshell to execute it.
And lastly, i have added a PRINT statement to print out the command for verification
Declare #sql Varchar(8000)
Select #sql = 'bcp "SELECT FirstName, LastName '
+ 'FROM AdventureWorks2012.Person.Person '
+ 'ORDER BY LastName, Firstname" '
+ 'queryout C:\Users\David\Desktop\yes.txt -c -t, -T -S'
+ ##SERVERNAME
PRINT #sql -- Print out for verification
EXEC master..xp_cmdshell #sql
I have struggled with that problem almost whole yesterday and finally it comes out, that the "select" query is too complex (probably) to be processed by the xp_cmdshell command directly.
I have a query joining and aggregating many tables from different databases.
Trying to save its results to txt file directly via xp_cmdshell always resulted in the output presented by BrownEyeBoy, eventhought the select itself was working correctly.
I've bypassed this simply by inserting the results of the complex query into temporary table and then execute the xp_cmdshell on the temporary table like:
DECLARE
#SQL varchar(max)
, #path varchar(max) = 'D:\TMP\TMP_' + convert(varchar(10), convert(date, getdate(), 21)) + '.txt'
, #BCP varchar(8000)
;
INSERT INTO ##TMP
{COMPLEX SELECT}
;
SET #SQL = 'SELECT * FROM ##TMP;
SET #BCP = 'bcp "' + #sql + '" queryout "' + #path + '" -c -T -S.'
EXEC xp_cmdshell #bcp;
Not nice, but easy and working.
Put the complete bcp query in one not to change the line while writing bcp query.
You can write your query as:
Declare #sql Varchar(8000)
Select #sql = 'bcp "SELECT FirstName, LastName FROM AdventureWorks2012.Person.Person ORDER BY LastName, Firstname " queryout "C:\Users\David\Desktop\yes.txt" -Usa -Ppassw0rd -c -t, -T -S'
EXEC master..xp_cmdshell #sql

Execute BCP command in remote server

i am facing an issue while executing the BCP command in the remote server.
i have the following command in a batch file which executes a script file.
The script file process a temporary table and writes the records in temporary table to a file.
SQLCMD -SQA_Server236 -dtestdb -Usa -PPassword1 -i"D:\script\Writing to Files\Write to CSV.sql" -o"D:\script\script_logs.log"
--script files contains...
declare #table NVARCHAR(255)
declare #filename VARCHAR(100)
set #filename='C:\TextFile\abcd.csv'
set #table ='##Indexes_Add'
IF OBJECT_ID('tempdb..#Indexes_Add') IS NOT NULL
BEGIN
DROP TABLE ##Indexes_Add
END
CREATE TABLE ##Indexes_Add
(
id int IDENTITY(1,1) PRIMARY KEY,
alter_command NVARCHAR(MAX),
successfully_readded BIT NULL,
)
insert into ##Indexes_Add select 'a',0
insert into ##Indexes_Add select 'a',0
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..'+#table) IS NOT NULL
BEGIN
DECLARE
#sql NVARCHAR(MAX),
#cols NVARCHAR(MAX) = N'';
SELECT #cols += ',' + name
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID('tempdb..'+#table)
ORDER BY column_id;
SELECT #cols = STUFF(#cols, 1, 1, '');
SET #sql = N'EXEC master..xp_cmdshell ''bcp "SELECT '''''
+ REPLACE(#cols, ',', ''''',''''') + ''''' UNION ALL SELECT '
+ 'RTRIM(' + REPLACE(#cols, ',', '),RTRIM(') + ') FROM '
+ 'tempdb.dbo.'+#table + '" queryout "' + #filename + '" -c -t, -SQA_Server236 -Usa -PPassword1''';
EXEC sp_executesql #sql;
print #sql
END
My problem-:
When i run the above batch command in a batch file and i give my local server other than server name "QA_Server236" , i am getting the file "abcd.csv" created in my system but when i give the server name as "QA_Server236" the file is created in the remote machine i.e QA_Server236. But i want the file to be created in my system if the given server is a remote server say "QA_Server236"
Can anyone help me in this issue. i am not getting any method to do so.
If I'm right BCP does not allow saving result sets and/or logs to remote machines. But you could try to mount a folder on remote PC to a shared folder on your local machine and set the output location there, or maybe try using network path "\[YOURPC]....".As I'm not sure it works (actually, I think it won't), here's the only solution I can think of: add a line to your batch which moves the file(s) from the remote machine to your PC (xcopy or similar) after BCP finished executing (in batch, do this as "Call bcp.exe [params]" instead of just "bcp.exe ...")Hope this helps!

BCP out Error in SQL2000: SQLState = 37000, NativeError = 4060

I have created a proc that grabs all the user tables in a local DB on my machine. I want to be able to create a flat file of all my tables using BCP and SQL. Its a dummy database in SQL 2000 connecting through windows authentication. I have set my enviroment path variable in WinXP SP2. I have created new users to access the db, switched off my firewall, using trusted connection. I have tried dozens of forums, no luck.
In dos command prompt I get the same error.
SQLState = 37000, NativeError = 4060
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database requested in login '[HelpDesk-EasyPay'. Login fails.
Here is my SP:
#Path VARCHAR(100),
#UserName VARCHAR(15),
#PassWord VARCHAR(15),
#ServerName VARCHAR(15)
AS
set quoted_identifier off
set nocount on
declare #n int
declare #db varchar(40)
set #db=DB_NAME()
declare #TableName varchar(15)
declare #bcp varchar(200)
select identity(int,1,1) as tblNo,name tblname into #T from Sysobjects where xtype='u'
select #n=COUNT(*) from #T
WHILE (#n>0)
BEGIN
SELECT #TableName=tblname FROM #T WHERE tblno=#n
PRINT 'Now BCP out for table: ' + #TableName
SET #bcp = "master..xp_cmdshell 'BCP " + "[" + #db + ".." + #TableName + "]" + " OUT" + #Path + "" + #TableName+".txt -c -U" + #UserName + " -P" + #PassWord + " -S" + #ServerName + " -T" + "'"
EXEC(#bcp)
SET #n=#n-1
END
DROP TABLE #T
Can anyone advise. This seems to be a connection problem or BCP ? Not sure.
edit: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060
Your brackets are extending over the entire qualified table name - only the individual components should be bracketed:
bcp [HelpDesk-EasyPay].dbo.[customer] out d:\MSSQL\Data\customer.bcp -N -Utest -Ptest -T
should work, so you want:
SET #bcp = "master..xp_cmdshell 'BCP " + "[" + #db + "]..[" + #TableName + "]" + " OUT" + #Path + "" + #TableName+".txt -c -U" + #UserName + " -P" + #PassWord + " -S" + #ServerName + " -T" + "'"
in your code. It looks like the error message you gave was truncated, otherwise you would have been able to see that it was attempting to open database "[HelpDesk-EasyPay.dbo.customer]" which, of course, does not exist, and even if it did, you would then get an error that no table was specified.
I have the same issue for the OUT (the minus character kills everything event the ^ don't work)
I avoid it with the QUERYOUT. Like this :
SET #s = 'BCP "SELECT * FROM [HelpDesk-EasyPay].dbo.customers" QUERYOUT myfile.txt ...'
Maybe someone will come in handy: I have the same issue with SQL Server 2017. The reason was the square brackets around the database name.

What is a simple command line program or script to backup SQL server databases?

I've been too lax with performing DB backups on our internal servers.
Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript?
To backup a single database from the command line, use osql or sqlcmd.
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe"
-E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"
You'll also want to read the documentation on BACKUP and RESTORE and general procedures.
I use ExpressMaint.
To backup all user databases I do for example:
C:\>ExpressMaint.exe -S (local)\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\backupdir\ -DS
Schedule the following to backup all Databases:
Use Master
Declare #ToExecute VarChar(8000)
Select #ToExecute = Coalesce(#ToExecute + 'Backup Database ' + [Name] + ' To Disk = ''D:\Backups\Databases\' + [Name] + '.bak'' With Format;' + char(13),'')
From
Master..Sysdatabases
Where
[Name] Not In ('tempdb')
and databasepropertyex ([Name],'Status') = 'online'
Execute(#ToExecute)
There are also more details on my blog: how to Automate SQL Server Express Backups.
I found this on a Microsoft Support page http://support.microsoft.com/kb/2019698.
It works great! And since it came from Microsoft, I feel like it's pretty legit.
Basically there are two steps.
Create a stored procedure in your master db. See msft link or if it's broken try here: http://pastebin.com/svRLkqnq
Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.
sqlcmd -S YOUR_SERVER_NAME\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases #backupLocation='C:\SQL_Backup\', #backupType='F'" 1>c:\SQL_Backup\backup.log
Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\SQL_Backup
I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:
#!/usr/bin/ksh
#
#.....
(
tsql -S {database} -U {user} -P {password} <<EOF
select * from {table}
go
quit
EOF
) >{output_file.dump}
You can use the backup application by ApexSQL. Although it’s a GUI application, it has all its features supported in CLI. It is possible to either perform one-time backup operations, or to create a job that would back up specified databases on the regular basis. You can check the switch rules and exampled in the articles:
ApexSQL Backup CLI support
ApexSQL Backup CLI examples
Eventual if you don't have a trusted connection as the –E switch declares
Use following command line
"[program dir]\[sql server version]\Tools\Binn\osql.exe" -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak'" -S [server] –U [login id] -P [password]
Where
[program dir] is the directory where the osql.exe exists
On 32bit OS c:\Program Files\Microsoft SQL Server\
On 64bit OS c:\Program Files (x86)\Microsoft SQL Server\
[sql server version] your sql server version 110 or 100 or 90 or 80 begin with the largest number
[server] your servername or server ip
[login id] your ms-sql server user login name
[password] the required login password
Microsoft's answer to backing up all user databases on SQL Express is here:
The process is: copy, paste, and execute their code (see below. I've commented some oddly non-commented lines at the top) as a query on your database server. That means you should first install the SQL Server Management Studio (or otherwise connect to your database server with SSMS). This code execution will create a stored procedure on your database server.
Create a batch file to execute the stored procedure, then use Task Scheduler to schedule a periodic (e.g. nightly) run of this batch file. My code (that works) is a slightly modified version of their first example:
sqlcmd -S .\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases #backupLocation='E:\SQLBackups\', #backupType='F'"
This worked for me, and I like it. Each time you run it, new backup files are created. You'll need to devise a method of deleting old backup files on a routine basis. I already have a routine that does that sort of thing, so I'll keep a couple of days' worth of backups on disk (long enough for them to get backed up by my normal backup routine), then I'll delete them. In other words, I'll always have a few days' worth of backups on hand without having to restore from my backup system.
I'll paste Microsoft's stored procedure creation script below:
--// Copyright © Microsoft Corporation. All Rights Reserved.
--// This code released under the terms of the
--// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
CREATE PROCEDURE [dbo].[sp_BackupDatabases]
#databaseName sysname = null,
#backupType CHAR(1),
#backupLocation nvarchar(200)
AS
SET NOCOUNT ON;
DECLARE #DBs TABLE
(
ID int IDENTITY PRIMARY KEY,
DBNAME nvarchar(500)
)
-- Pick out only databases which are online in case ALL databases are chosen to be backed up
-- If specific database is chosen to be backed up only pick that out from #DBs
INSERT INTO #DBs (DBNAME)
SELECT Name FROM master.sys.databases
where state=0
AND name=#DatabaseName
OR #DatabaseName IS NULL
ORDER BY Name
-- Filter out databases which do not need to backed up
IF #backupType='F'
BEGIN
DELETE #DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
END
ELSE IF #backupType='D'
BEGIN
DELETE #DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE IF #backupType='L'
BEGIN
DELETE #DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE
BEGIN
RETURN
END
-- Declare variables
DECLARE #BackupName varchar(100)
DECLARE #BackupFile varchar(100)
DECLARE #DBNAME varchar(300)
DECLARE #sqlCommand NVARCHAR(1000)
DECLARE #dateTime NVARCHAR(20)
DECLARE #Loop int
-- Loop through the databases one by one
SELECT #Loop = min(ID) FROM #DBs
WHILE #Loop IS NOT NULL
BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
SET #DBNAME = '['+(SELECT DBNAME FROM #DBs WHERE ID = #Loop)+']'
-- Set the current date and time n yyyyhhmmss format
SET #dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
IF #backupType = 'F'
SET #BackupFile = #backupLocation+REPLACE(REPLACE(#DBNAME, '[',''),']','')+ '_FULL_'+ #dateTime+ '.BAK'
ELSE IF #backupType = 'D'
SET #BackupFile = #backupLocation+REPLACE(REPLACE(#DBNAME, '[',''),']','')+ '_DIFF_'+ #dateTime+ '.BAK'
ELSE IF #backupType = 'L'
SET #BackupFile = #backupLocation+REPLACE(REPLACE(#DBNAME, '[',''),']','')+ '_LOG_'+ #dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
IF #backupType = 'F'
SET #BackupName = REPLACE(REPLACE(#DBNAME,'[',''),']','') +' full backup for '+ #dateTime
IF #backupType = 'D'
SET #BackupName = REPLACE(REPLACE(#DBNAME,'[',''),']','') +' differential backup for '+ #dateTime
IF #backupType = 'L'
SET #BackupName = REPLACE(REPLACE(#DBNAME,'[',''),']','') +' log backup for '+ #dateTime
-- Generate the dynamic SQL command to be executed
IF #backupType = 'F'
BEGIN
SET #sqlCommand = 'BACKUP DATABASE ' +#DBNAME+ ' TO DISK = '''+#BackupFile+ ''' WITH INIT, NAME= ''' +#BackupName+''', NOSKIP, NOFORMAT'
END
IF #backupType = 'D'
BEGIN
SET #sqlCommand = 'BACKUP DATABASE ' +#DBNAME+ ' TO DISK = '''+#BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +#BackupName+''', NOSKIP, NOFORMAT'
END
IF #backupType = 'L'
BEGIN
SET #sqlCommand = 'BACKUP LOG ' +#DBNAME+ ' TO DISK = '''+#BackupFile+ ''' WITH INIT, NAME= ''' +#BackupName+''', NOSKIP, NOFORMAT'
END
-- Execute the generated SQL command
EXEC(#sqlCommand)
-- Goto the next database
SELECT #Loop = min(ID) FROM #DBs where ID>#Loop
END​
Here is an example one, it will take backup database, compress using 7zip and delete backup file so issue related to storage also solved. In this example I use 7zip, which is free
#echo off
CLS
echo Running dump ...
sqlcmd -S SERVER\SQLEXPRESS -U username -P password -Q "BACKUP DATABASE master TO DISK='D:\DailyDBBackup\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak'"
echo Zipping ...
"C:\Program Files\7-Zip\7z.exe" a -tzip "D:\DailyDBBackup\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%_%time:~0,2%%time:~3,2%%time:~6,2%.bak.zip" "D:\DailyDBBackup\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak"
echo Deleting the SQL file ...
del "D:\DailyDBBackup\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak"
echo Done!
Save this as sqlbackup.bat and schedule it to be run everyday.
If you just want to take backup only then you can create script without zipping and deleting.
You could use a VB Script I wrote exactly for this purpose:
https://github.com/ezrarieben/mssql-backup-vbs/
Schedule a task in the "Task Scheduler" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.
SET NOCOUNT ON;
declare #PATH VARCHAR(200)='D:\MyBackupFolder\'
-- path where you want to take backups
IF OBJECT_ID('TEMPDB..#back') IS NOT NULL
DROP TABLE #back
CREATE TABLE #back
(
RN INT IDENTITY (1,1),
DatabaseName NVARCHAR(200)
)
INSERT INTO #back
SELECT 'MyDatabase1'
UNION SELECT 'MyDatabase2'
UNION SELECT 'MyDatabase3'
UNION SELECT 'MyDatabase4'
-- your databases List
DECLARE #COUNT INT =0 , #RN INT =1, #SCRIPT NVARCHAR(MAX)='', #DBNAME VARCHAR(200)
PRINT '---------------------FULL BACKUP SCRIPT-------------------------'+CHAR(10)
SET #COUNT = (SELECT COUNT(*) FROM #back)
PRINT 'USE MASTER'+CHAR(10)
WHILE(#COUNT > = #RN)
BEGIN
SET #DBNAME =(SELECT DatabaseName FROM #back WHERE RN=#RN)
SET #SCRIPT ='BACKUP DATABASE ' +'['+#DBNAME+']'+CHAR(10)+'TO DISK =N'''+#PATH+#DBNAME+ N'_Backup_'
+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.bak'''+CHAR(10)+'WITH COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)
PRINT #SCRIPT
SET #RN=#RN+1
END
PRINT '---------------------DIFF BACKUP SCRIPT-------------------------'+CHAR(10)
SET #COUNT =0 SET #RN =1 SET #SCRIPT ='' SET #DBNAME =''
SET #COUNT = (SELECT COUNT(*) FROM #back)
PRINT 'USE MASTER'+CHAR(10)
WHILE(#COUNT > = #RN)
BEGIN
SET #DBNAME =(SELECT DatabaseName FROM #back WHERE RN=#RN)
SET #SCRIPT ='BACKUP DATABASE ' +'['+#DBNAME+']'+CHAR(10)+'TO DISK =N'''+#PATH+#DBNAME+ N'_Backup_'
+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.diff'''+CHAR(10)+'WITH DIFFERENTIAL, COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)
PRINT #SCRIPT
SET #RN=#RN+1
END
This can be helpful when you are dealing with dockerised mssql container in your day to day work and want to take a quick dump of the data from table. I have specially found it useful when you are re-building the db container quite frequently and don't want to loose the test data after the re-build.
Export data using bcp utility
/opt/mssql-tools/bin/bcp <Table_Name> out /tmp/MyData.bcp -d <database_name> -c -U <user_name> -P "<password>" -S <server_name>
Import data using bcp utility
/opt/mssql-tools/bin/bcp <Table_Name> IN /tmp/MyData.bcp -d <database_name> -c -U <user_name> -P "<password>" -S <server_name>
If you can find the DB files... "cp DBFiles backup/"
Almost for sure not advisable in most cases, but it's simple as all getup.

Resources