SE の雑記

SQL Server の情報をメインに Microsoft 製品の勉強内容を日々投稿

SQL Server 2016 CTP 2.0 の JSON サポートを使ってみる

leave a comment

SQL Server 2016 では、クエリの実行結果を JSON の形式で取得することができます。

詳細については、Format Query Results as JSON with FOR JSON (SQL Server) を参照していただければと。
ほかには、JSON Support in SQL Server 2016 も参考になります。

  • CTP 2 では、FOR JSON による出力結果の JSON 形式のサポート
  • CTP 3 では、OPEN JSON による JSON 形式の内容の入力のサポート

が使用できるようです。

日本語ではぺんぺん師匠が解説されているのでこちらも参考になります。
SQL Server 2016でJSONに対応します

まだ、ヘルプは用意されていないようですが、JSON Functions として、以下のような関数も用意されるようです。#
# CTP 3 のタイミングで情報公開されるのでしょうかね。

    We will also provide set of useful functions for parsing and processing JSON text. JSON built-in functions that will be available in SQL Server 2016 CTP3 are:

    • ISJSON( jsonText ) that checks is the NVARCHAR text input properly formatted according to the JSON specification. You can use this function the create check constraints on NVARCHAR columns that contain JSON text,
    • JSON_VALUE( jsonText, path ) that parses jsonText and extracts scalar value on the specified JavaScript-like path (see below some JSON path examples),

 

SQL Server の JSON サポートは JSON データ型があるのではなく、検索結果を JSON として扱うものとなるため、データを JSON の形式で格納しておきたいというような場合には文字列型等に入れておく必要があるようです。

単純な実行結果としては、以下のようになります。

SELECT * FROM sys.objects FOR JSON AUTO

image

冒頭で紹介した情報にも記載されていますが、実行結果が多い場合には複数の行として結果が取得されますので、アプリケーションで扱う際にはこの辺は注意しておいた方がよいかと。

The result set contains a single column. A small result set may contain a single row. A large result set contains multiple rows.

以下のように、連結しないといけないのでしょうかね。

# ConvertFrom-JSON はさくっと変換できるのか気になって入れてみました。

$connectionString = "Data Source=localhost; Integrated Security=true;";
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connectionString = "Data Source=localhost; Integrated Security=true";
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandType = [System.Data.CommandType]::Text
$command.CommandText = "SELECT * FROM sys.objects FOR JSON AUTO"
$reader = $command.ExecuteReader()
$sb = New-Object System.Text.StringBuilder
while($reader.Read())
{
    $sb.Append($reader[0]) | Out-Null
}
$json = ($sb.ToString() | ConvertFrom-Json)
$command.Dispose()
$connection.Close()
$connection.Dispose()
Share

Written by Masayuki.Ozawa

6月 22nd, 2015 at 8:03 pm

Posted in SQL Server

Tagged with

Leave a Reply