commands

^

Write-DbaDbTableData

Author Chrissy LeMaire (@cl), netnerds.net
Availability Windows, Linux, macOS

 

Aliases : Write-DbaDataTable

Synopsis

Writes data to a SQL Server table.

Description

Writes a .NET DataTable to a SQL Server table using SQL Bulk Copy.

Syntax

Write-DbaDbTableData -SqlInstance <DbaInstanceParameter>
    [-SqlCredential <PSCredential>]
    [-Database <Object>] -InputObject <Object>
    [-Table] <String>
    [[-Schema] <String>]
    [-BatchSize <Int32>]
    [-NotifyAfter <Int32>]
    [-AutoCreateTable]
    [-NoTableLock]
    [-CheckConstraints]
    [-FireTriggers]
    [-KeepIdentity]
    [-KeepNulls]
    [-Truncate]
    [-BulkCopyTimeOut <Int32>]
    [-ColumnMap <Hashtable>]
    [-EnableException]
    [-UseDynamicStringLength]
    [-WhatIf]
    [-Confirm]
    [<CommonParameters>]

 

Examples

 

Example: 1
PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
PS C:\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers

Performs a bulk insert of all the data in customers.csv into database mydb, schema dbo, table customers. A progress bar will be shown as rows are inserted. If the destination table does not exist,
the import will be halted.

Example: 2
PS C:\> $tableName = "MyTestData"
PS C:\> $query = "SELECT name, create_date, owner_sid FROM sys.databases"
PS C:\> $dataset = Invoke-DbaQuery -SqlInstance 'localhost,1417' -SqlCredential $containerCred -Database master -Query $query -As DataSet
PS C:\> $dataset | Write-DbaDbTableData -SqlInstance 'localhost,1417' -SqlCredential $containerCred -Database tempdb -Table $tableName -AutoCreateTable

Pulls data from a SQL Server instance and then performs a bulk insert of the dataset to a new, auto-generated table tempdb.dbo.MyTestData.

Example: 3
PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
PS C:\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -AutoCreateTable -Confirm

Performs a bulk insert of all the data in customers.csv. If mydb.dbo.customers does not exist, it will be created with inefficient but forgiving DataTypes.
Prompts for confirmation before a variety of steps.

Example: 4
PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
PS C:\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -Truncate

Performs a bulk insert of all the data in customers.csv. Prior to importing into mydb.dbo.customers, the user is informed that the table will be truncated and asks for confirmation. The user is
prompted again to perform the import.

Example: 5
PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
PS C:\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Database mydb -Table customers -KeepNulls

Performs a bulk insert of all the data in customers.csv into mydb.dbo.customers. Because Schema was not specified, dbo was used. NULL values in the destination table will be preserved.

Example: 6
PS C:\> $passwd = ConvertTo-SecureString "[email protected]" -AsPlainText -Force
PS C:\> $AzureCredential = New-Object System.Management.Automation.PSCredential("AzureAccount"),$passwd)
PS C:\> $DataTable = Import-Csv C:\temp\customers.csv
PS C:\> Write-DbaDbTableData -SqlInstance AzureDB.database.windows.net -InputObject $DataTable -Database mydb -Table customers -KeepNulls -SqlCredential $AzureCredential -BulkCopyTimeOut 300

This performs the same operation as the previous example, but against a SQL Azure Database instance using the required credentials.

Example: 7
PS C:\> $process = Get-Process
PS C:\> Write-DbaDbTableData -InputObject $process -SqlInstance sql2014 -Table "[[DbName]]].[Schema.With.Dots].[`"[Process]]`"]" -AutoCreateTable

Creates a table based on the Process object with over 60 columns, converted from PowerShell data types to SQL Server data types. After the table is created a bulk insert is performed to add process
information into the table
Writes the results of Get-Process to a table named: "[Process]" in schema named: Schema.With.Dots in database named: [DbName]
The Table name, Schema name and Database name must be wrapped in square brackets [ ]
Special characters like " must be escaped by a ` character.
In addition any actual instance of the ] character must be escaped by being duplicated.
This is an example of the type conversion in action. All process properties are converted, including special types like TimeSpan. Script properties are resolved before the type conversion starts
thanks to ConvertTo-DbaDataTable.

Example: 8
PS C:\> $server = Connect-DbaInstance -SqlInstance SRV1
PS C:\> $server.Invoke("CREATE TABLE tempdb.dbo.test (col1 INT, col2 VARCHAR(100))")
PS C:\> $data = Invoke-DbaQuery -SqlInstance $server -Query "SELECT 123 AS value1, 'Hello world' AS value2" -As DataSet
PS C:\> $data | Write-DbaDbTableData -SqlInstance $server -Table 'tempdb.dbo.test' -ColumnMap @{ value1 = 'col1' ; value2 = 'col2' }

The dataset column 'value1' is inserted into SQL column 'col1' and dataset column value2 is inserted into the SQL Column 'col2'. All other columns are ignored and therefore null or default values.

Required Parameters

-SqlInstance

The target SQL Server instance or instances.

Alias
Required True
Pipeline false
Default Value
-InputObject

This is the DataTable (or data row) to import to SQL Server. It is very important to understand how different types of objects are beeing processed to get the best performance. The best performance is achieved when using the DataSet data type. If the data to be imported are determined with Invoke-DbaQuery, the option "-As DataSet" should be used. Then all records are imported in a single call of SqlBulkCopy. Also the data type DataTable can lead to an import of all records in a single call of SqlBulkCopy. However, it should be noted that "$varWithDataTable | Write-DbaDbTableData" causes the pipeline to convert the single object of type DataTable to a series of objects of type DataRow. These in turn lead to single calls of SqlBulkCopy per record, which negatively affects performance. This is also the reason why the use of the DataRow data type is generally discouraged. When using objects of type PSObject, these are first all combined into an internal object of type DataTable and then imported in a single call of SqlBulkCopy.

Alias DataTable
Required True
Pipeline true (ByValue)
Default Value
-Table

The table name to import data into. You can specify a one, two, or three part table name. If you specify a one or two part name, you must also use -Database. If the table does not exist, you can use -AutoCreateTable to automatically create the table. The table will be created with sub-optimal data types such as nvarchar(max). If the object has special characters please wrap them in square brackets [ ]. Using dbo.First.Table will try to import to a table named 'Table' on schema 'First' and database 'dbo'. The correct way to import to a table named 'First.Table' on schema 'dbo' is by passing dbo.[First].[Table]. Any actual usage of the ] must be escaped by duplicating the ] character. The correct way to import to a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]].

Alias
Required True
Pipeline false
Default Value

Optional Parameters

-SqlCredential

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.

Alias
Required False
Pipeline false
Default Value
-Database

The database where the Input Object data will be written.

Alias
Required False
Pipeline false
Default Value
-Schema

Defaults to dbo if no schema is specified.

Alias
Required False
Pipeline false
Default Value dbo
-BatchSize

The BatchSize for the import defaults to 50000.

Alias
Required False
Pipeline false
Default Value 50000
-NotifyAfter

Sets the option to show the notification after so many rows of import. Defaults to 5000 rows.

Alias
Required False
Pipeline false
Default Value 5000
-AutoCreateTable

If this switch is enabled, the table will be created if it does not already exist. The table will be created with sub-optimal data types such as nvarchar(max).

Alias
Required False
Pipeline false
Default Value False
-NoTableLock

If this switch is enabled, a table lock (TABLOCK) will not be placed on the destination table. By default, this operation will lock the destination table while running.

Alias
Required False
Pipeline false
Default Value False
-CheckConstraints

If this switch is enabled, the SqlBulkCopy option to process check constraints will be enabled. Per Microsoft "Check constraints while data is being inserted. By default, constraints are not checked."

Alias
Required False
Pipeline false
Default Value False
-FireTriggers

If this switch is enabled, the SqlBulkCopy option to fire insert triggers will be enabled. Per Microsoft "When specified, cause the server to fire the insert triggers for the rows being inserted into the Database."

Alias
Required False
Pipeline false
Default Value False
-KeepIdentity

If this switch is enabled, the SqlBulkCopy option to preserve source identity values will be enabled. Per Microsoft "Preserve source identity values. When not specified, identity values are assigned by the destination."

Alias
Required False
Pipeline false
Default Value False
-KeepNulls

If this switch is enabled, the SqlBulkCopy option to preserve NULL values will be enabled. 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."

Alias
Required False
Pipeline false
Default Value False
-Truncate

If this switch is enabled, the destination table will be truncated after prompting for confirmation.

Alias
Required False
Pipeline false
Default Value False
-BulkCopyTimeOut

Value in seconds for the BulkCopy operations timeout. The default is 30 seconds.

Alias
Required False
Pipeline false
Default Value 5000
-ColumnMap

By default, the bulk insert tries to automap columns. When it doesn't work as desired, this parameter will help. Check out the examples for more information.

Alias
Required False
Pipeline false
Default Value
-EnableException

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.

Alias
Required False
Pipeline false
Default Value False
-UseDynamicStringLength

By default, all string columns will be NVARCHAR(MAX). If this switch is enabled, all columns will get the length specified by the column's MaxLength property (if specified).

Alias
Required False
Pipeline false
Default Value False
-WhatIf

If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.

Alias wi
Required False
Pipeline false
Default Value
-Confirm

If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.

Alias cf
Required False
Pipeline false
Default Value

 

Want to see the source code for this command? Check out Write-DbaDbTableData on GitHub.
Want to see the Bill Of Health for this command? Check out Write-DbaDbTableData.