SQL Server 使用JSON DATA而不使用OPENJSON并按值搜索

ar7v8xwq  于 2022-12-26  发布在  其他
关注(0)|答案(2)|浏览(131)
[
    {
        "Level"       : "S1",
        "Major"       : "Teknik Informatika"
    },
    {
        "Level"       : "SMA",
        "Major"       : "IPA"
    },
    {
        "Level"       : "SMP",
        "Major"       : "Umum"
    },
    {
        "Level"       : "SD",
        "Major"       : "Umum"
  }
]
iD  | UserID  | Education
------------------------------------------------------------------------------
1   | B000-1  | [{"Level":"S1","Major":"TI"},{"Level":"SMA","Major":"IPA"}]
2   | B000-2  | [{"Level":"SMA","Major":"IPS"},{"Level":"SD","Major":"Umum"}]
3   | B000-3  | [{"Level":"SMA","Major":"IPA"}]
4   | B000-4  | [{"Level":"SD","Major":"Umum"}]

我可以设置目录表Education显示对象数据,输入数据Education[Level]='SMA'存储数据OPENJSON,存储数据SQL Server 2012
翻译:如果Education表中的每一列都包含如上所述的对象,那么如果不使用OPENJSON,我如何找到Education[Level]='SMA',因为我使用的是SQL Server 2012

iD  | UserID  | Education
------------------------------------------------------------------------------
1   | B000-1  | [{"Level":"S1","Major":"TI"},{"Level":"SMA","Major":"IPA"}]
2   | B000-2  | [{"Level":"SMA","Major":"IPS"},{"Level":"SD","Major":"Umum"}]
3   | B000-3  | [{"Level":"SMA","Major":"IPA"}]
ogsagwnx

ogsagwnx1#

请尝试以下解决方案。
我们将JSON数据转换为基于属性的XML。例如,对于第一行,它将如下所示:

<root>
    <r Level="S1" Major="TI"/>
    <r Level="NotSMA" Major="IPA"/>
</root>

然后,使用XQuery方法.exist()搜索@Level参数。

    • SQL语言**
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Education NVARCHAR(MAX));
INSERT @tbl (Education) VALUES
(N'[{"Level":"S1","Major":"TI"},{"Level":"NotSMA","Major":"IPA"}]'),
(N'[{"Level":"SMA","Major":"IPS"},{"Level":"SD","Major":"Umum"}]'),
(N'[{"Level":"SMA","Major":"IPA"}]');
-- DDL and sample data population, end

DECLARE @separator CHAR(4) = '},{"'
    , @Level VARCHAR(20) = 'SMA';

SELECT * 
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST('<root><r ' + 
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Education, '":', '=')
        , ',"', SPACE(1))
        , '}]', '')
        , '[{"', ''), @separator, '/><r ') + 
        '/></root>' AS XML)) AS t1(c)
WHERE c.exist('/root/r[@Level=sql:variable("@Level")]') = 1;
    • 产出**

| 识别号|教育|
| - ------| - ------|
| 第二章|[{"级别":" SMA ","严重":" IPS "},{"级别":" SD ","严重":" Umum "}]|
| 三个|[{"级别":" SMA ","主要":"国际音标"}]|

bksxznpy

bksxznpy2#

快速搜索后找到Consuming JSON Strings in SQL Server
在这里,作者展示了“旧”版本的SQL Server如何读/写JSON对象/字符串。解决方案需要根据您的需要进行定制,因为您的JSON结构不同,但这是可能的。
或者,您也可以像上面建议的PM 77-1那样强制like

相关问题