arrays
  • sql-server
  • json
  • tsql
  • 2017-03-03 5 views 0 likes 
    0

    SQL Server 2016でJSON機能を使用しています。変数を使用して、$ .people []配列の項目を以下のように参照するにはどうすればよいですか? JSON_QUERY関数のpathパラメーターに "1"をハードコーディングする代わりに、変数を使用してpeople配列の各項目をループしたいと思います。T-SQLでjsonオブジェクトの配列項目を参照する方法

    declare @json nvarchar(max) = '{ 
        "people": [{ 
         "name": "John", 
         "surname": "Doe" 
        }, { 
         "name": "Jane", 
         "surname": null, 
         "active": true 
        }] 
    }'; 
    
    select JSON_QUERY(@json,'$.people[1]'); -- this works 
    declare @test nvarchar(max) = '$.people[1]'; 
    select JSON_QUERY(@json,@test); -- ERROR: The argument 2 of the "JSON_VALUE or  JSON_QUERY" must be a string literal. 
    

    答えて

    0

    動的SQLは、sp_executesqlプロシージャを使用して使用できます。

    元のselectステートメントとsp_executesqlステートメントの両方に、下に同じ出力が表示されています。

    declare @json nvarchar(max) = '{ 
        "people": [{ 
         "name": "John", 
         "surname": "Doe" 
        }, { 
         "name": "Jane", 
         "surname": null, 
         "active": true 
        }] 
    }'; 
    
    declare @i int = 1 
    declare @dyn_sql nvarchar(1000) = 
        'select json_query(@json_dyn, ''$.people[' + cast(@i as varchar(10)) + ']'');' 
    
    select JSON_QUERY(@json,'$.people[1]'); -- this works 
    
    exec sp_executesql @dyn_sql --set the SQL to run 
        , N'@json_dyn nvarchar(max)' --"declare" the variable in the SQL to run 
        , @json_dyn = @json --"set" the variable in the SQL to run 
    
    /* 
    Output : {   "name": "Jane",   "surname": null,   "active": true  } 
    */ 
    
    関連する問題