如何删除存储在SQL Server列中的JSON属性?

use*_*456 3 sql-server json

我有一项任务是删除保存在SQL Server数据库表的列中的JSON属性.这是我桌子的结构

OrderId   Name   JSON
Run Code Online (Sandbox Code Playgroud)

JSON列中,我有这个JSON数据:

{ 
    "Property1" :"",
    "Property2" :"",
    "metadata-department": "A",
    "metadata-group": "B"
}
Run Code Online (Sandbox Code Playgroud)

我有超过500条具有此json值的记录.

我可以更新要删除的所有记录metadata-department吗?

Den*_*s W 9

这个问题已经过时了,但我想我会为那些可能通过搜索引擎来到这里的人发布另一个解决方案.

在SQL Server 2016或SQL Azure中,以下工作:

DECLARE @info NVARCHAR(100) = '{"name":"John","skills":["C#","SQL"]}'

PRINT JSON_MODIFY(@info, '$.name', NULL)

-- Result: {"skills":["C#","SQL"]}
Run Code Online (Sandbox Code Playgroud)

资料来源:https://msdn.microsoft.com/en-us/library/dn921892.aspx

  • 值得一提的是,这种方法仅在您处于 *lax* 模式(这是默认模式)时才有效,如果您处于 *strict* 模式,那么这会将节点的值设置为 `null` 而不是将其删除. (4认同)

Eva*_*kas 0

在我的 SQL Server 环境中,我安装了 CLR RegEx Replace 函数并使用这些函数,我已经实现了您想要的:

DECLARE @Text NVARCHAR(MAX) = '{ 
    "Property1" :"",
    "Property2" :"",
    "metadata-department": "A",
    "metadata-group": "B"
}';

PRINT dbo.RegExReplace(@Text, '"metadata-department": "[A-Za-z0-z]",\r\n\s+', '');
Run Code Online (Sandbox Code Playgroud)

结果:

{ 
    "Property1" :"",
    "Property2" :"",
    "metadata-group": "B"
}
Run Code Online (Sandbox Code Playgroud)

CLR 来源:https://www.simple-talk.com/sql/t-sql-programming/clr-assemble-regex-functions-for-sql-server-by-example/