如何在数据库列的JSON值中将字符串替换为int?

时间:2018-11-15 14:56:14

标签: sql json sql-server tsql sql-server-2016

我根据下表为用户使用默认响应。

表:USERS | ID | NAME |默认响应

默认响应包含JSON格式的字符串。我需要将所有relatives_birthdays的月份和日期从字符串更改为int。

这是以前的json的示例:

[
 {
  "id":1,
  "relatives_birthdays":[ 
  { 
    "month":"8",
    "day": "1",
    "description": "Birthday mother"
  }, 
  { 
    "month":"3",
    "day": "27",
    "description": "Birthday brother"
  }, 
  { 
    "month":"4",
    "day": "12",
    "description": "Birthday father"
  }
  ]
 },
 {
  "id":2,
  "relatives_birthdays":[ 
  { 
    "month":"12",
    "day": "11",
    "description": "Birthday mother"
  }, 
  { 
    "month":"1",
    "day": "2",
    "description": "Birthday brother"
  }, 
  { 
    "month":"7",
    "day": "18",
    "description": "Birthday father"
  }
  ]
 }
]

这是我需要的json:

[
 {
  "id":1,
  "relatives_birthdays":[ 
  { 
    "month": 8,
    "day": 1,
    "description": "Birthday mother"
  }, 
  { 
    "month": 3,
    "day": 27,
    "description": "Birthday brother"
  }, 
  { 
    "month": 4,
    "day": 12,
    "description": "Birthday father"
  }
  ]
 },
 {
  "id":2,
  "relatives_birthdays":[ 
  { 
    "month": 12,
    "day": 11,
    "description": "Birthday mother"
  }, 
  { 
    "month": 1,
    "day": 2,
    "description": "Birthday brother"
  }, 
  { 
    "month": 7,
    "day": 18,
    "description": "Birthday father"
  }
  ]
 }
]

要完成此操作,我需要执行有关脚本的任何想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用const DropdownExampleClearable = () => <Dropdown clearable options={options} selection /> 解析json,然后重新构建。可以,但是效率可能很低:

openjson

这是生成的json:

declare @j nvarchar(max) = '[
 {
  "id":1,
  "relatives_birthdays":[ 
  { 
    "month":"8",
    "day": "1",
    "description": "Birthday mother"
  }, 
  { 
    "month":"3",
    "day": "27",
    "description": "Birthday brother"
  }, 
  { 
    "month":"4",
    "day": "12",
    "description": "Birthday father"
  }
  ]
 },
 {
  "id":2,
  "relatives_birthdays":[ 
  { 
    "month":"12",
    "day": "11",
    "description": "Birthday mother"
  }, 
  { 
    "month":"1",
    "day": "2",
    "description": "Birthday brother"
  }, 
  { 
    "month":"7",
    "day": "18",
    "description": "Birthday father"
  }
  ]
 }
]'

select rt.[id]
 , relatives_birthdays.[month]
 , relatives_birthdays.[day]
 , relatives_birthdays.[description]
from (
 select p.id
 from openjson(@j) with (id int) p
 ) as rt
inner join (
 select p.id
  , c.month
  , c.day
  , c.description
 from openjson(@j) with (
   id int
   , relatives_birthdays nvarchar(max) as json
   ) p
 cross apply openjson(relatives_birthdays) with (
   month int
   , day int
   , description nvarchar(max)
   ) c
 ) as relatives_birthdays
 on rt.id = relatives_birthdays.id
for json auto