SQL Server JSON_Modify,如何更新全部?

时间:2016-12-29 16:46:16

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

我正在尝试使用Json_Modify的值更新所有列:

DECLARE @JSON NVARCHAR(MAX)
SET @JSON = 
N'{
"A":1,
"TMP": [    
    {"A":"VALUE1", "B": "VALUE2", "C": 1},
    {"A":"VALUE3", "B": "VALUE4", "C": 2},
    {"A":"VALUE5", "B": "VALUE6", "C": 3}]}
'

SET @JSON = JSON_MODIFY(@JSON, '$.TMP.A', 'JEJE')

SELECT * FROM OPENJSON(@JSON, '$.TMP') WITH ( A NCHAR(10), B NCHAR(10), C INT )

我需要更新所有列" A"与" JEJE"例如,它无法正常工作。

3 个答案:

答案 0 :(得分:3)

以下是两个选项。免责声明:我不是通过sql server 2016的JSON专家,但我已经将一些东西混在一起。

选项1:您显然是从JSON字符串创建结果集。为什么不创建结果集然后更新呢?

DECLARE @jsontable TABLE (A varchar(50), b varchar(50), c varchar(50))
DECLARE @JSON NVARCHAR(MAX)

SET @JSON = 
N'{
"A":1,
"TMP": [    
    {"A":"VALUE1", "B": "VALUE2", "C": 1},
    {"A":"VALUE3", "B": "VALUE4", "C": 2},
    {"A":"VALUE5", "B": "VALUE6", "C": 3}]}
'

--SET @JSON = JSON_MODIFY(@JSON, '$.TMP.A', 'JEJE')
INSERT INTO @jsontable (a,b,c)
SELECT * FROM OPENJSON(@JSON, '$.TMP') WITH ( A NCHAR(10), B NCHAR(10), C INT )

UPDATE @jsontable 
SET a = 'JEJE' 

SELECT * 
FROM @jsontable

选项2:您可以操作JSON组件,但必须将索引传递给函数。

DECLARE @JSON NVARCHAR(MAX)
SET @JSON = 
N'{
"A":1,
"TMP": [    
    {"A":"VALUE1", "B": "VALUE2", "C": 1},
    {"A":"VALUE3", "B": "VALUE4", "C": 2},
    {"A":"VALUE5", "B": "VALUE6", "C": 3}]}
'

SET @JSON = JSON_MODIFY(@JSON, '$.TMP[0].A', 'JEJE')
SET @JSON = JSON_MODIFY(@JSON, '$.TMP[1].A', 'JEJE')
SET @JSON = JSON_MODIFY(@JSON, '$.TMP[2].A', 'JEJE')

SELECT * FROM OPENJSON(@JSON, '$.TMP') WITH ( A NCHAR(10), B NCHAR(10), C INT )

答案 1 :(得分:0)

我认为这会有所帮助:

CREATE PROCEDURE SP__SYSTEM___UPDATE_COLUMN_FROM_JSON
    @JSON NVARCHAR(MAX) OUTPUT,
    @COLUMN VARCHAR(50),
    @NEW_VALUE VARCHAR(50)
AS
BEGIN
    DECLARE @QUERY NVARCHAR(MAX)
    DECLARE @INDEX INT = 0

    WHILE @INDEX < (SELECT COUNT(*) FROM OPENJSON(@JSON))
    BEGIN
        SELECT @QUERY = CONCAT(N'SELECT @JSON = JSON_MODIFY(@JSON, ''$[', @INDEX, N'].',@COLUMN,''', ',@NEW_VALUE,')')
        EXEC SP_EXECUTESQL @QUERY, N'@JSON NVARCHAR(MAX) OUTPUT', @JSON = @JSON OUTPUT
        SET @INDEX = @INDEX + 1
    END
END

然后像这样执行它:

BEGIN
    DECLARE @JSON VARCHAR(MAX) = '[{"ID":1,"USERID":0},{"ID":2,"USERID":0},{"ID":3,"USERID":0}]'
    EXEC SP__SYSTEM___UPDATE_COLUMN_FROM_JSON @JSON OUTPUT, 'USERID', '100'
    SELECT @JSON
END

答案 2 :(得分:0)

如果要将数组存储在字段中,则可以执行以下操作:

UPDATE some_table SET
    some_field = '[' + (
        SELECT
            STRING_AGG(JSON_MODIFY([value],'$.A', 'JEJE'), ',') WITHIN GROUP (ORDER BY CAST([key] AS int))
        FROM
            OPENJSON(some_field)
    ) + ']'