LewisMCT333
LewisMCT333

Reputation: 105

.BAT File to Execute SQL Query (Backup)

I have an SQL script which is as follows:-

   BACKUP DATABASE [**********] TO  DISK = N'G:\Super Sacred Databases\Orderwise Backup\20-04-2017-13-05.bak' WITH NOFORMAT, NOINIT,  NAME = N'**********-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

On the server I wish to run a .bat file that i can schedule on windows task scheduler.

My confusion is, how do i write a .bat file to execute this query on the SQL Server?

I have so far tried to use this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q ?

The problem is that is doesnt work at all for me, furthermore i have no idea what the -Q ? would be to run a specific query in SQL Server.

Furthermore im not sure exactly how to specify the Servername or Databasename in the fields required.

I know im new to this, but im trying hard.

Thanks in advance for your help!

CONTINUED -

Now i am working with this

sqlcmd -U s******a -P 0****! -S LPSERVER\ORDERWISE 
-Q "BACKUP DATABASE [********Live] TO  DISK = N'G:\Super Sacred Databases\Orderwise Backup\20-04-2017-13-05.bak' WITH NOFORMAT, NOINIT,  NAME = N'******estLive-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
"

But it just doesnt seem to do anything just shows the cmd line in the CMD interface and does nothing more.

Any suggestions?

Upvotes: 1

Views: 3011

Answers (1)

Heinzi
Heinzi

Reputation: 172270

Since BACKUP DATABASE can be executed in the context of any database, you can just skip the -d parameter.

The "server name" is usually the Windows name of the PC running the SQL server instance, optionally extended by \InstanceName, if you are not running the default instance of SQL Server. For the local PC, you can simply use . as the server name.

-Q contains the query you are executing:

sqlcmd -U myLogin -P myPassword -S MyServerName -Q "BACKUP DATABASE ..."

Upvotes: 1

Related Questions