Advertisement
Ruslan_Rayanov

JSON in SQL Server examples

Apr 9th, 2022 (edited)
1,421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.65 KB | None | 0 0
  1. DECLARE @json NVARCHAR(4000)
  2. SET @json =
  3. N'{
  4.    "info":{  
  5.      "type":1,
  6.  
  7.      "address":{  
  8.        "town":"Bristol",
  9.        "county":"Avon",
  10.        "country":"England"
  11.      },
  12.      "tags":["Sport", "Water polo"]
  13.   },
  14.   "type":"Basic"
  15. }'
  16.  
  17. SELECT JSON_VALUE(@json, '$.info.address.town')
  18. SELECT JSON_QUERY(@json, '$.info.tags')
  19.  
  20. SELECT * FROM OPENJSON(@json, '$.info')
  21.  
  22.  
  23. SELECT top 2 id, header FROM as_trace FOR JSON  auto
  24. --FOR JSON  auto
  25. FOR JSON PATH, ROOT('Orders')
  26.  
  27.  
  28. select isjson(@json)
  29.  
  30.  
  31. -------------
  32. declare @s nvarchar(max) = '{
  33.    "Orders":
  34.    [
  35.        {
  36.        "Order": {
  37.            "Number": "S043659",
  38.            "Date": "2011-05-31T00:00:00"
  39.        },
  40.        "Account": "Microsoft",
  41.        "Item": {
  42.            "Price": 59.99,
  43.            "Quantity": 1
  44.        }
  45.        },
  46.        {
  47.            "Order": {
  48.                "Number": "S043661",
  49.                "Date": "2011-06-01T00:00:00"
  50.            },
  51.            "Account": "Nokia",
  52.            "Item": {
  53.                "Price": 24.99,
  54.                "Quantity": 3
  55.            }
  56.        }
  57.    ]
  58. }'
  59.  
  60. SELECT JSON_VALUE(Value, N'$.Order.Number') Number,
  61.      JSON_VALUE(Value, N'$.Order.Date') Date,
  62.      JSON_VALUE(Value, N'$.Account') Customer,
  63.      JSON_VALUE(Value, N'$.Item.Quantity') Quantity
  64.  
  65.  
  66. FROM OPENJSON(@s, N'$.Orders')
  67.  
  68. SELECT *
  69. FROM OPENJSON(@s, N'$.Orders')
  70. WITH (
  71.     Number      VARCHAR(200)    N'$.Order.Number',
  72.     Date        DATETIME        N'$.Order.Date',
  73.     Customer    VARCHAR(200)    N'$.Account',
  74.     Quantity    INT             N'$.Item.Quantity',
  75.     obj    nvarchar(max)   '$.obj' as JSON
  76. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement