27

I have a .sql script and I want to build a database from it. How to do it in sqlcmd? I know it's like:

CREATE DATABASE dbName
GO

But how to specify the .sql script and location to build the database?

rene
  • 41,474
  • 78
  • 114
  • 152
Cobold
  • 2,563
  • 6
  • 34
  • 51

5 Answers5

19

Use @Jeremiah Peschka's answer to supply the sqlcmd utility with the script to execute.

As for the location for the newly created database, it can be specified as part of the CREATE DATABASE command:

CREATE DATABASE dbName
ON (
  NAME = dbName_dat,
  FILENAME = 'D:\path\to\dbName.mdf'
)
LOG ON (
  NAME = dbName_log,
  FILENAME = 'D:\path\to\dbName.ldf'
)

As you can see from the linked article, you can specify other properties as well, like initial size, maximum size etc.

Andriy M
  • 76,112
  • 17
  • 94
  • 154
  • Hey @AER, thank you for [your contribution](https://stackoverflow.com/review/suggested-edits/19480583). I've decided to reject it as irrelevant because the question was clearly about running a script stored in a file rather than typing and executing the command(s) in a terminal session. When a script is meant to be run as a single batch, ending it with a `GO` is optional (perhaps you already know that). – Andriy M Apr 19 '18 at 05:59
17

This is very simple. Just enter following command to run sqlcmd:
sqlcmd -U sa -P password
Then enter:

CREATE DATABASE MYDB
GO

This will create the db. Then enter "quit" to exit.

Bart
  • 19,692
  • 7
  • 68
  • 77
Badar
  • 1,430
  • 1
  • 15
  • 19
13

without a file:

sqlcmd -Q "CREATE DATABASE HelloWorld"
Chad Grant
  • 44,326
  • 9
  • 65
  • 80
11
sqlcmd -i C:\path\to\file.sql

More options can be found in SQL Server books online.

0

use this: sqlcmd -i "c:\my scripts\my script.sql"

see sqlcmd description at MS for other options

Laszlo T
  • 1,165
  • 10
  • 22