9

I would like to have a BAT file open a sql server script. Currently I have this code in the sql file:

declare @path varchar(255), @mydb varchar(50)
SELECT @mydb = 'timeclockplus'
select @path = 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Backup\' 
            + @mydb + '-' + convert(varchar(8),getdate(),112) + '.bak'
BACKUP DATABASE @mydb TO DISK = @path

How do I open this SQL file from a BAT file?

I am currently trying to run it like this:

C:\Program Files\Microsoft SQL Server\80\Tools\Binn\osql -E 
   -S Sql server-hl7\timeclockplus timeclockplus.sql -oresults.txt

but OSQL does not exist in the BINN directory,

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

4 Answers4

16

You should invoke the sqlcmd command-line tool from your batch file. Assuming your sql file is "backup.sql", the command line would be something like:

sqlcmd -E -S yoursqlinstance -i backup.sql

-E uses trusted connection, replace with -U and -P if you need to specify a SQL username and password. See also this article with examples.

driis
  • 161,458
  • 45
  • 265
  • 341
4
sqlcmd -S 127.0.0.1 /E -i MySqlScript.sql

Replace /E with /U and /P if you don't have trusted connection

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
3

If you want a much better answer, here it is:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: batch file for sql query
SET FIELDVAL=Empty
SET DBNAME=MYDB
SET SQLSTRING=SELECT column_name(s)^
 FROM table_name1^
 INNER JOIN table_name2^
 ON table_name1.column_name=table_name2.column_name^
 AND table_name2.field=%FIELDVAL%
ECHO !SQLSTRING!

ECHO.
sqlcmd.exe -b -S localhost -E -d !DBNAME! -Q "!SQLSTRING!" -W
ECHO Query is done. Hit any key to close this window....
pause>nul
djangofan
  • 28,471
  • 61
  • 196
  • 289
0

Start > Run > Type Cmd.

MyDrive:\Mypath\Mybat.bat

=)

ajdams
  • 2,276
  • 14
  • 20