Load SQL Server data from flat file (CSV / TSV / TXT)

mssql-cmd - SQL Server interactive and batch query command-line tool »

Download mssql-cmd Free Trial »

mssql-cmd loads delimited text files into SQL Server in interactive or batch mode. With header=y, the first line is matched to table column names, so the file can contain a subset of columns or list them in a different order.

parameters:

delimiter: delimiter char ("|", ",", "#", "TAB", "WHITESPACE")

quote: quote char (quote="'" or quote="chr(34)")

header: y|n, the first line contains field names

schema: schema name (for MySQL: database name)

table: table name

datafile: data file name

filetype: txt|tsv|csv|json|jsonl

loadtype: append|replace|update|upsert
    append: append rows to the table.
    replace: delete all rows, then load.
    update: update existing rows by updatekey.
    upsert: insert or update by updatekey.

updatekey: key field used by update/upsert, usually the primary key

dateformat: date format (e.g. "YYYY-MM-DD HH24:MI:SS")

timestampformat: timestamp format (e.g. "YYYY-MM-DD HH24:MI:SS.FF6")

nullif: value to load as NULL ("BLANKS" for empty strings)

badfile: write rows that cannot be loaded to this file

errors: maximum number of errors

buffer: commit/fetch batch size

Interactive example

mssql-cmd> load table=orders
      > datafile=e:\temp\orders.csv
      > delimiter=","
      > quote="chr(34)"
      > header=y
      > loadtype=replace
      > dateformat="YYYY-MM-DD HH24:MI:SS"
      > timestampformat="YYYY-MM-DD HH24:MI:SS.FF6";

Batch example

mssql-cmd dsn="user:password@host:1433/dbname" task=load table=orders datafile=e:\temp\orders.csv delimiter="," quote="chr(34)" header=y loadtype=replace quit=y

See also: load into another schema/database, load CLOB/TEXT data, export data.