< Back

Import-DbaCsv

Mon Jan 13, 2020 11:59 am

NAME Import-DbaCsv



SYNOPSIS

Efficiently imports very large (and small) CSV files into SQL Server.





SYNTAX

Import-DbaCsv [[-Path] <System.Object[]>] [-SqlInstance]

<Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter[]> [[-SqlCredential] <Pscredential>] [-Database]

<String> [[-Table] <String>] [[-Schema] <String>] [-Truncate <Switch>] [[-Delimiter] <Char>] [-SingleColumn

<Switch>] [[-BatchSize] <Int>] [[-NotifyAfter] <Int>] [-TableLock <Switch>] [-CheckConstraints <Switch>]

[-FireTriggers <Switch>] [-KeepIdentity <Switch>] [-KeepNulls <Switch>] [[-Column] <System.String[]>]

[[-ColumnMap] <System.Collections.Hashtable[]>] [-KeepOrdinalOrder <Switch>] [-AutoCreateTable <Switch>]

[-NoProgress <Switch>] [-NoHeaderRow <Switch>] [-UseFileNameForSchema <Switch>] [[-Quote] <Char>] [[-Escape]

<Char>] [[-Comment] <Char>] [[-TrimmingOption] <String>] [[-BufferSize] <Int>] [[-ParseErrorAction] <String>]

[[-Encoding] <String>] [[-NullValue] <String>] [[-MaxQuotedFieldLength] <Int>] [-SkipEmptyLine <Switch>]

[-SupportsMultiline <Switch>] [-UseColumnDefault <Switch>] [-NoTransaction <Switch>] [-EnableException <Switch>]

[<CommonParameters>]





DESCRIPTION

Import-DbaCsv takes advantage of .NET's super fast SqlBulkCopy class to import CSV files into SQL Server.



The entire import is performed within a transaction, so if a failure occurs or the script is aborted, no changes

will persist.



If the table or view specified does not exist and -AutoCreateTable, it will be automatically created using slow

and inefficient but accommodating data types.



This importer supports fields spanning multiple lines. The only restriction is that they must be quoted, otherwise

it would not be possible to distinguish between malformed data and multi-line values.





PARAMETERS

-AutoCreateTable [<Switch>]

Creates a table if it does not already exist. The table will be created with sub-optimal data types such as

nvarchar(max)



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-BatchSize [<Int>]

Specifies the batch size for the import. Defaults to 50000.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-BufferSize [<Int>]

Defines the default buffer size. The default BufferSize is 4096.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-CheckConstraints [<Switch>]

If this switch is enabled, the SqlBulkCopy option to check constraints will be used.



Per Microsoft "Check constraints while data is being inserted. By default, constraints are not checked."



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Column [<System.String[]>]

Import only specific columns. To remap column names, use the ColumnMap.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-ColumnMap [<System.Collections.Hashtable[]>]

By default, the bulk copy tries to automap columns. When it doesn't work as desired, this parameter will help.

Check out the examples for more information.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Comment [<Char>]

Defines the default comment character indicating that a line is commented out. Default is #.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Database [<String>]

Specifies the name of the database the CSV will be imported into. Options for this this parameter are

auto-populated from the server.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Delimiter [<Char>]

Specifies the delimiter used in the imported file(s). If no delimiter is specified, comma is assumed.



Valid delimiters are '`t`, '|', ';',' ' and ',' (tab, pipe, semicolon, space, and comma).



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-EnableException [<Switch>]

By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.

This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables

advanced scripting.

Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own

try/catch.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Encoding [<String>]

By default, set to UTF-8.



The encoding of the file.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Escape [<Char>]

Defines the default escape character letting insert quotation characters inside a quoted field.



The escape character can be the same as the quote character.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-FireTriggers [<Switch>]

If this switch is enabled, the SqlBulkCopy option to allow insert triggers to be executed will be used.



Per Microsoft "When specified, cause the server to fire the insert triggers for the rows being inserted into

the database."



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-KeepIdentity [<Switch>]

If this switch is enabled, the SqlBulkCopy option to keep identity values from the source will be used.



Per Microsoft "Preserve source identity values. When not specified, identity values are assigned by the

destination."



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-KeepNulls [<Switch>]

If this switch is enabled, the SqlBulkCopy option to keep NULL values in the table will be used.



Per Microsoft "Preserve null values in the destination table regardless of the settings for default values.

When not specified, null values are replaced by default values where applicable."



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-KeepOrdinalOrder [<Switch>]

By default, the importer will attempt to map exact-match columns names from the source document to the target

table. Using this parameter will keep the ordinal order instead.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-MaxQuotedFieldLength [<Int>]

The maxmimum length (in bytes) for any quoted field.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-NoHeaderRow [<Switch>]

By default, the first row is used to determine column names for the data being imported.



Use this switch if the first row contains data and not column names.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-NoProgress [<Switch>]

The progress bar is pretty but can slow down imports. Use this parameter to quietly import.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-NotifyAfter [<Int>]

Specifies the import row count interval for reporting progress. A notification will be shown after each group

of this many rows has been imported.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-NoTransaction [<Switch>]

Do not use a transaction when performing the import.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-NullValue [<String>]

The value which denotes a DbNull-value.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-ParseErrorAction [<String>]

By default, the parse error action throws an exception and ends the import.



You can also choose AdvanceToNextLine which basically ignores parse errors.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Path [<System.Object[]>]

Specifies path to the CSV file(s) to be imported. Multiple files may be imported at once.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Quote [<Char>]

Defines the default quote character wrapping every field.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Schema [<String>]

Specifies the schema in which the SQL table or view where CSV will be imported into resides. Default is dbo.



If a schema does not currently exist, it will be created, after a prompt to confirm this. Authorization will

be set to dbo by default.



This parameter overrides -UseFileNameForSchema.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-SingleColumn [<Switch>]

Specifies that the file contains a single column of data. Otherwise, the delimiter check bombs.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-SkipEmptyLine [<Switch>]

Skip empty lines.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-SqlCredential [<Pscredential>]

Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).



Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory -

Integrated are all supported.



For MFA support, please use Connect-DbaInstance.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-SqlInstance [<Sqlcollaborative.Dbatools.Parameter.DbaInstanceParameter[]>]

The SQL Server Instance to import data into.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-SupportsMultiline [<Switch>]

Indicates if the importer should support multiline fields.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Table [<String>]

Specifies the SQL table or view where CSV will be imported into.



If a table name is not specified, the table name will be automatically determined from the filename.



If the table specified does not exist and -AutoCreateTable, it will be automatically created using slow and

inefficient but accommodating data types.



If the automatically generated table datatypes do not work for you, please create the table prior to import.



If you want to import specific columns from a CSV, create a view with corresponding columns.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-TableLock [<Switch>]

If this switch is enabled, the SqlBulkCopy option to acquire a table lock will be used. This is automatically

used if -Turbo is enabled.



Per Microsoft "Obtain a bulk update lock for the duration of the bulk copy operation. When not

specified, row locks are used."



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-TrimmingOption [<String>]

Determines which values should be trimmed. Default is "None". Options are All, None, UnquotedOnly and

QuotedOnly.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-Truncate [<Switch>]

If this switch is enabled, the destination table will be truncated prior to import.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-UseColumnDefault [<Switch>]

Use the column default values if the field is not in the record.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



-UseFileNameForSchema [<Switch>]

If this switch is enabled, the script will try to find the schema name in the input file by looking for a

period (.) in the file name.



If used with the -Table parameter you may still specify the target table name. If -Table is not used the file

name after the first period will

be used for the table name.



For example test.data.csv will import the csv contents to a table in the test schema.



If it finds one it will use the file name up to the first period as the schema. If there is no period in the

filename it will default to dbo.



If a schema does not currently exist, it will be created, after a prompt to confirm this. Authorization will

be set to dbo by default.



This behaviour will be overridden if the -Schema parameter is specified.



Required? false

Position? named

Default value

Accept pipeline input? False

Accept wildcard characters? false



<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug,

ErrorAction, ErrorVariable, WarningAction, WarningVariable,

OutBuffer, PipelineVariable, and OutVariable. For more information, see

about_CommonParameters (https:/go.microsoft.com/fwlink/?LinkID=113216).



INPUTS



OUTPUTS



NOTES





Tags: Migration, Import

Author: Chrissy LeMaire (@cl), netnerds.net



Website: https://dbatools.io

Copyright: (c) 2018 by dbatools, licensed under MIT

License: MIT https://opensource.org/licenses/MIT



-------------------------- EXAMPLE 1 --------------------------



PS C:\\>Import-DbaCsv -Path C:\\temp\\housing.csv -SqlInstance sql001 -Database markets



Imports the entire comma-delimited housing.csv to the SQL "markets" database on a SQL Server named sql001, using

the first row as column names.



Since a table name was not specified, the table name is automatically determined from filename as "housing".

-------------------------- EXAMPLE 2 --------------------------



PS C:\\>Import-DbaCsv -Path .\\housing.csv -SqlInstance sql001 -Database markets -Table housing -Delimiter "`t"

-NoHeaderRow



Imports the entire tab-delimited housing.csv, including the first row which is not used for colum names, to the

SQL markets database, into the housing table, on a SQL Server named sql001.

-------------------------- EXAMPLE 3 --------------------------



PS C:\\>Import-DbaCsv -Path C:\\temp\\huge.txt -SqlInstance sqlcluster -Database locations -Table latitudes

-Delimiter "|"



Imports the entire pipe-delimited huge.txt to the locations database, into the latitudes table on a SQL Server

named sqlcluster.

-------------------------- EXAMPLE 4 --------------------------



PS C:\\>Import-DbaCsv -Path c:\\temp\\SingleColumn.csv -SqlInstance sql001 -Database markets -Table TempTable

-SingleColumn



Imports the single column CSV into TempTable

-------------------------- EXAMPLE 5 --------------------------



PS C:\\>Get-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb

-AutoCreateTable



Imports every CSV in the \\\\FileServer\\csvs path into both sql001 and sql002's tempdb database. Each CSV will be

imported into an automatically determined table name.

-------------------------- EXAMPLE 6 --------------------------



PS C:\\>Get-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb

-AutoCreateTable -WhatIf



Shows what would happen if the command were to be executed

-------------------------- EXAMPLE 7 --------------------------



PS C:\\>Import-DbaCsv -Path c:\\temp\\dataset.csv -SqlInstance sql2016 -Database tempdb -Column Name, Address, Mobile



Import only Name, Address and Mobile even if other columns exist. All other columns are ignored and therefore null

or default values.

-------------------------- EXAMPLE 8 --------------------------



PS C:\\>Import-DbaCsv -Path C:\\temp\\schema.data.csv -SqlInstance sql2016 -database tempdb -UseFileNameForSchema



Will import the contents of C:\\temp\\schema.data.csv to table 'data' in schema 'schema'.

-------------------------- EXAMPLE 9 --------------------------



PS C:\\>Import-DbaCsv -Path C:\\temp\\schema.data.csv -SqlInstance sql2016 -database tempdb -UseFileNameForSchema

-Table testtable



Will import the contents of C:\\temp\\schema.data.csv to table 'testtable' in schema 'schema'.

-------------------------- EXAMPLE 10 --------------------------



PS C:\\>$columns = @{



>> Text = 'FirstName'

>> Number = 'PhoneNumber'

>> }

PS C:\\> Import-DbaCsv -Path c:\\temp\\supersmall.csv -SqlInstance sql2016 -Database tempdb -ColumnMap $columns



The CSV column 'Text' is inserted into SQL column 'FirstName' and CSV column Number is inserted into the SQL

Column 'PhoneNumber'. All other columns are ignored and therefore null or default values.



RELATED LINKS

https://dbatools.io/Import-DbaCsv