从存储在SQL Server列中的json对象中删除数组

时间:2017-12-06 15:46:36

标签: json sql-server

如果我在SQL Server的列中存储了以下JSON:

declare @json nvarchar(max) = '[{"id": "1", "name": "test1"},{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]'

如何删除Id:= 1的数组?

我想得到以下结果:

[{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]

1 个答案:

答案 0 :(得分:0)

试试这个:

    declare @json nvarchar(max) = '[{"id": "1", "name": "test1"},{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]';


    DECLARE @IdTobeRemoved INT =1;
    DECLARE @StartIndex INT
    DECLARE @EndIndex INT
    DECLARE @tempjson nvarchar(max)



    SELECT @StartIndex = CHARINDEX('"id": "'+CONVERT(VARCHAR(10),@IdTobeRemoved)+'"',@json)-2


    SELECT @tempjson = STUFF(@json, 1, @StartIndex, '')


    SELECT @EndIndex = 
                CASE WHEN SUBSTRING(@tempjson,CHARINDEX('}',@tempjson)+1,1)=']'
                    THEN CHARINDEX('}',@tempjson)+1
                    ELSE CHARINDEX('}',@tempjson)+2
                END


    SELECT REPLACE(REPLACE(@json,SUBSTRING(@tempjson,0,@EndIndex),''),'},]','}]')