17
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowershellでSQLServerにSQLを実行するスクリプト

Last updated at Posted at 2018-11-20

各行の先頭の型宣言はあってもなくても動きます。

なるべく行を少なくしてわかりやすいように記述してみました。

ExecSQL.ps1
# SqlConnectionStringBuilder を使用してSQL接続の設定を保存する
[object]$ConnectionString = New-Object -TypeName System.Data.SqlClient.SqlConnectionStringBuilder
[object]$ConnectionString['Data Source'] = "localhost\SQLEXPRESS" #SQLServerのホスト\インスタンスを指定
[object]$ConnectionString['Initial Catalog'] = "HOGEHOGE" #データベースを指定
[object]$ConnectionString['Integrated Security'] = "TRUE" #Windows統合認証を利用する場合は"TRUE"

# SQL文の文字列を設定する
[string]$SQLQuery = "SELECT * FROM [dbo].[hogehoge]"

# DataTableを利用してSQL実行結果を一時格納
[object]$resultsDataTable = New-Object System.Data.DataTable

# SQLConnection、SQLCommandを設定する
[object]$SqlConnection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)
[object]$SqlCommand = New-Object System.Data.SQLClient.SQLCommand($SQLQuery, $SqlConnection)

# データベースへ接続
[object]$SqlConnection.Open()

# ExecuteReaderを実行してDataTableにデータを格納
[object]$resultsDataTable.Load($SqlCommand.ExecuteReader())

# データベース接続解除
[object]$SqlConnection.Close()

#format-tableで画面表示
[object]$resultsDataTable | format-table 

# CSVへ保存する場合はexport-csv
[object]$resultsDataTable | export-csv hogehoge.csv -Encoding default -NoTypeInformation

.NET Frameworkを活用できるからPowerShellは便利ですね。

17
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?