[英]Export from SQL Server to json text file using PowerShell
如果您在以下情況下應該閱讀本文:您正在嘗試了解如何將 SQL 服務器數據轉換為 JSON 並將其放入文本 .json 文件中
題:
有人能告訴我這段代碼有什么問題嗎? 我的目標是從 SQL Server 表中讀取數據,將其轉換為 JSON,然后將結果保存為 JSON 文本文件。 代碼運行,但生成的.json
文件只有:
{
"FieldCount": 11
},
{
一遍又一遍地重復,僅此而已。
我的代碼:
$instance = "localhost\SQLEXPRESS"
$connectionString = "Server=$Instance; Database=myDB;Integrated Security=True;"
$query = "Select * from myTable"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$result | ConvertTo-Json | Out-File "file.json"
$connection.Close()
更新:
從技術上講,他/她會回答我最初的問題(盡管我會警告並說我還沒有嘗試過),因此會將答案授予 postanote。
但是,我會推薦 Mike 的答案或我最終使用 BCP 的答案:
bcp "select * from myTable FOR JSON AUTO" queryout "C:\filepath\testsml.json" -c -S ".\SQLEXPRESS" -d myDBName -T
嘗試這樣的事情......
### Exporting SQL Server table to JSON
Clear-Host
#--Establishing connection to SQL Server --#
$InstanceName = "."
$connectionString = "Server=$InstanceName;Database=msdb;Integrated Security=True;"
#--Main Query --#
$query = "SELECT * FROM sysjobs"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($result)
#--Exporting data to the screen --#
$table | select $table.Columns.ColumnName | ConvertTo-Json
$connection.Close()
# Results
{
"job_id": "5126aca3-1003-481c-ab36-60b45a7ee757",
"originating_server_id": 0,
"name": "syspolicy_purge_history",
"enabled": 1,
"description": "No description available.",
"start_step_id": 1,
"category_id": 0,
"owner_sid": [
1
],
"notify_level_eventlog": 0,
"notify_level_email": 0,
"notify_level_netsend": 0,
"notify_level_page": 0,
"notify_email_operator_id": 0,
"notify_netsend_operator_id": 0,
"notify_page_operator_id": 0,
"delete_level": 0,
"date_created": "\/Date(1542859767703)\/",
"date_modified": "\/Date(1542859767870)\/",
"version_number": 5
}
如果您使用 sql server express 2016 或更高版本,您應該能夠使用 FOR JSON 子句在數據庫端執行此操作。 嘗試類似的東西
$instance = "localhost\SQLEXPRESS"
$connectionString = "Server=$Instance; Database=myDB;Integrated Security=True;"
$query = "Select * from myTable FOR JSON AUTO"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.ExecuteScalar() | Out-File "file.json"
這里的“問題”是,即使使用執行標量,SQL 命令FOR JSON AUTO
也會截斷 JSON 輸出,並且輸出到帶有VARCHAR(max)
的變量仍然會截斷。 如果重要,請使用與 Visual Studio 捆綁的 SQL 2016 LocalDB。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.