-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample.SqlServerDataMovement.ps1
More file actions
80 lines (72 loc) · 2.59 KB
/
Copy pathExample.SqlServerDataMovement.ps1
File metadata and controls
80 lines (72 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
param(
[string] $Server = $(if ($env:DBACLIENTX_SQLSERVER) { $env:DBACLIENTX_SQLSERVER } else { 'localhost' }),
[string] $Database = $(if ($env:DBACLIENTX_SQLDATABASE) { $env:DBACLIENTX_SQLDATABASE } else { 'tempdb' }),
[int] $RowCount = 100,
[switch] $KeepTable
)
# Use this example to verify that the installed DbaClientX module can write
# PowerShell objects into SQL Server through the provider-neutral bulk cmdlet
# and read the loaded row count back.
# Example:
# .\Example.SqlServerDataMovement.ps1 -Server localhost -Database tempdb -RowCount 100
Import-Module DbaClientX -Force
$tableName = 'DbaClientXDataMovement_' + ([guid]::NewGuid().ToString('N').Substring(0, 12))
$destinationTable = "dbo.$tableName"
$connectionString = New-DbaXConnectionString `
-Provider SqlServer `
-Server $Server `
-Database $Database `
-TrustServerCertificate
try {
Invoke-DbaXNonQuery -Server $Server -Database $Database -TrustServerCertificate -Query @"
CREATE TABLE $destinationTable
(
Id int NOT NULL,
DisplayName nvarchar(100) NOT NULL,
Score decimal(18,2) NOT NULL,
CreatedUtc datetime2 NOT NULL
);
"@ -ErrorAction Stop | Out-Null
$rows = 1..$RowCount | ForEach-Object {
[pscustomobject]@{
Id = $_
DisplayName = "Row $_"
Score = [decimal]($_ * 1.25)
CreatedUtc = [datetime]::UtcNow
}
}
$writeResult = $rows | Invoke-DbaXBulkInsert `
-Provider SqlServer `
-ConnectionString $connectionString `
-DestinationTable $destinationTable `
-BatchSize 5000 `
-PassThru `
-ErrorAction Stop
$readBack = Invoke-DbaXQuery `
-Server $Server `
-Database $Database `
-TrustServerCertificate `
-Query "SELECT COUNT(*) AS [RowsLoaded], MIN(Id) AS [MinId], MAX(Id) AS [MaxId], CAST(SUM(Score) AS decimal(18,2)) AS [ScoreSum] FROM $destinationTable;" `
-ReturnType PSObject `
-ErrorAction Stop
[pscustomobject]@{
Server = $Server
Database = $Database
DestinationTable = $destinationTable
WrittenRows = $writeResult.Rows
ReadRows = $readBack.RowsLoaded
MinId = $readBack.MinId
MaxId = $readBack.MaxId
ScoreSum = $readBack.ScoreSum
}
}
finally {
if (-not $KeepTable) {
Invoke-DbaXNonQuery `
-Server $Server `
-Database $Database `
-TrustServerCertificate `
-Query "IF OBJECT_ID(N'$destinationTable', N'U') IS NOT NULL DROP TABLE $destinationTable;" `
-ErrorAction SilentlyContinue | Out-Null
}
}