[How-To] Import large .sql file into MSSQL (Microsoft SQL) Server

Objective: You have a .sql file you wish to import in Microsoft SQL Server (MSSQL)

Solution: Microsoft has a command line utility called Sqlcmd that can be used to import very large datasets into SQL server without having to open the file.  More information on this utility can be found here: http://msdn.microsoft.com/en-us/library/ms162773.aspx

Here is a snippit of the utility and its available switches before beginning:

C:\Users\Administrator>sqlcmd /?

usage: Sqlcmd            [-U login id]          [-P password]
  [-S server]            [-H hostname]          [-E trusted connection]
  [-N Encrypt Connection][-C Trust Server Certificate]
  [-d use database name] [-l login timeout]     [-t query timeout]
  [-h headers]           [-s colseparator]      [-w screen width]
  [-a packetsize]        [-e echo input]        [-I Enable Quoted Identifiers]
  [-c cmdend]            [-L[c] list servers[clean output]]
  [-q "cmdline query"]   [-Q "cmdline query" and exit]
  [-m errorlevel]        [-V severitylevel]     [-W remove trailing spaces]
  [-u unicode output]    [-r[0|1] msgs to stderr]
  [-i inputfile]         [-o outputfile]        [-z new password]
  [-f  | i:[,o:]] [-Z new password and exit]
  [-k[1|2] remove[replace] control characters]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-p[1] print statistics[colon format]]
  [-R use client regional setting]
  [-K application intent]
  [-M multisubnet failover]
  [-b On error batch abort]
  [-v var = "value"...]  [-A dedicated admin connection]
  [-X[1] disable commands, startup script, environment variables [and exit]]
  [-x disable variable substitution]
  [-? show syntax summary]

Here is an example of how to use the utility:

  1. Open up a command prompt
    1. Note: Administrative privileges are optional depending on how you have your security settings configured.
      Server 2012 - Administrative Command Prompt
  2. Execute the following command
    1. sqlcmd -S SERVERNAME\INSTANCE_NAME -i C:\path\mysqlfile.sql
      1. Here are some notes/tricks you might want to use:
        • If you are using the default instance when you installed MSSQL server, you don't have to specify \INSTANCE_NAME
        • You can log results to a text file by appending the following switch: -o C:\path\results.txt
        • You can specify a database to import to by appending the following switch: -d MYDATABASE
        • You can specify username and password by appending the following switch: -u USERNAME -p PASSWORD
          --Note: You can wait to be prompted for credentials by optionally leaving out the -p switch, however if you are piping the results out to notepad, the command will not fully execute.

 

Leave a Reply

Your email address will not be published. Required fields are marked *