{"id":15002983,"url":"https://github.com/scottgriv/sql-mssql_openjson_example","last_synced_at":"2026-03-14T16:04:27.796Z","repository":{"id":196431088,"uuid":"696093810","full_name":"scottgriv/sql-mssql_openjson_example","owner":"scottgriv","description":"An example query that demonstrates how to use the OPENJSON function in Microsoft SQL Server.","archived":false,"fork":false,"pushed_at":"2025-10-18T00:57:35.000Z","size":451,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-13T21:13:37.261Z","etag":null,"topics":["database","json","microsoft-sql-server","microsoft-sql-server-management-studio","microsoft-sqlserver-database","mssql","mssql-database","mssql-server","open-json","openjson","sql","sql-server","sql-server-database","stack-overflow","stack-overflow-answers","stackoverflow","stackoverflow-answer"],"latest_commit_sha":null,"homepage":"","language":"SQL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"unlicense","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/scottgriv.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-09-25T04:22:06.000Z","updated_at":"2025-10-18T00:57:38.000Z","dependencies_parsed_at":null,"dependency_job_id":"7d87bc53-043b-4af5-a589-94385baff10a","html_url":"https://github.com/scottgriv/sql-mssql_openjson_example","commit_stats":null,"previous_names":["scottgriv/sql-openjson_example","scottgriv/sql-mssql_openjson_example"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/scottgriv/sql-mssql_openjson_example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottgriv%2Fsql-mssql_openjson_example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottgriv%2Fsql-mssql_openjson_example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottgriv%2Fsql-mssql_openjson_example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottgriv%2Fsql-mssql_openjson_example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/scottgriv","download_url":"https://codeload.github.com/scottgriv/sql-mssql_openjson_example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottgriv%2Fsql-mssql_openjson_example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28032523,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-25T02:00:05.988Z","response_time":58,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","json","microsoft-sql-server","microsoft-sql-server-management-studio","microsoft-sqlserver-database","mssql","mssql-database","mssql-server","open-json","openjson","sql","sql-server","sql-server-database","stack-overflow","stack-overflow-answers","stackoverflow","stackoverflow-answer"],"created_at":"2024-09-24T18:54:33.769Z","updated_at":"2025-12-25T16:26:21.495Z","avatar_url":"https://github.com/scottgriv.png","language":"SQL","funding_links":["https://www.buymeacoffee.com/scottgriv"],"categories":[],"sub_categories":[],"readme":"\u003c!-- Begin README --\u003e\n\n\u003cdiv align=\"center\"\u003e\n    \u003ca href=\"https://github.com/scottgriv/sql-mssql_openjson_example\" target=\"_blank\"\u003e\n        \u003cimg src=\"./docs/images/icon.png\" width=\"150\" height=\"150\"/\u003e\n    \u003c/a\u003e\n\u003c/div\u003e\n\u003cbr\u003e\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://www.microsoft.com/en-us/sql-server/sql-server-2022\"\u003e\u003cimg src=\"https://img.shields.io/badge/Microsoft_SQL_Server-2022-CC2927?style=for-the-badge\u0026logo=microsoftsqlserver\" alt=\"SQL Server Badge\" /\u003e\u003c/a\u003e\n    \u003ca href=\"https://www.json.org/json-en.html\"\u003e\u003cimg src=\"https://img.shields.io/badge/JSON-2020--12-000000?style=for-the-badge\u0026logo=json\" alt=\"JSON Badge\" /\u003e\u003c/a\u003e\n    \u003ca href=\"https://stackoverflow.com/questions/73575888/how-to-perform-a-two-column-split-by-linking-your-data-in-sql-server\"\u003e\u003cimg src=\"https://img.shields.io/badge/Stack_Overflow-Answer-F58025?style=for-the-badge\u0026logo=stackoverflow\" alt=\"Stack Overflow Badge\" /\u003e\u003c/a\u003e\n    \u003cbr\u003e\n    \u003ca href=\"https://github.com/scottgriv\"\u003e\u003cimg src=\"https://img.shields.io/badge/github-follow_me-181717?style=for-the-badge\u0026logo=github\u0026color=181717\" alt=\"GitHub Badge\" /\u003e\u003c/a\u003e\n    \u003ca href=\"mailto:scott.grivner@gmail.com\"\u003e\u003cimg src=\"https://img.shields.io/badge/gmail-contact_me-EA4335?style=for-the-badge\u0026logo=gmail\" alt=\"Email Badge\" /\u003e\u003c/a\u003e\n    \u003ca href=\"https://www.buymeacoffee.com/scottgriv\"\u003e\u003cimg src=\"https://img.shields.io/badge/buy_me_a_coffee-support_me-FFDD00?style=for-the-badge\u0026logo=buymeacoffee\u0026color=FFDD00\" alt=\"BuyMeACoffee Badge\" /\u003e\u003c/a\u003e\n    \u003cbr\u003e\n    \u003ca href=\"https://prgportfolio.com\" target=\"_blank\"\u003e\u003cimg src=\"https://img.shields.io/badge/PRG-Bronze Project-CD7F32?style=for-the-badge\u0026logo=data:image/sv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MCAxNSAtNyA5IC0zNnoKbTExNiAtMTY5IGMwIC0yMyAtMyAtMjUgLTQ5IC0yNSAtNDAgMCAtNTAgMyAtNTQgMjAgLTMgMTQgLTE0IDIwIC0zMiAyMCAtMTgKMCAtMjkgLTYgLTMyIC0yMCAtNyAtMjUgLTIzIC0yNiAtMjMgLTIgMCAyOSA4IDMyIDEwMiAzMiA4NyAwIDg4IDAgODggLTI1eiIvPgo8L2c+Cjwvc3ZnPgo=\" alt=\"Bronze\" /\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n---------------\n\n\u003ch1 align=\"center\"\u003eMicrosoft SQL Server OPENJSON Example\u003c/h1\u003e\n\nAn example query that demonstrates how to use the `OPENJSON` function in `Microsoft SQL Server`.\n\n`OPENJSON` is a table-valued function that parses `JSON` text and returns objects and properties from the `JSON` input as rows and columns. `OPENJSON` provides a rowset view over a `JSON` document that is useful for applying relational operators like `PIVOT` and `UNPIVOT`. `OPENJSON` can be used as the target of an `INSERT`, `UPDATE`, or `DELETE` statement, just like a regular table or view.\n\n---------------\n\n## Table of Contents\n\n- [Getting Started](#getting-started)\n    - [Question](#question)\n    - [My Answer](#my-answer)\n- [Resources](#resources)\n- [License](#license)\n- [Credits](#credits)\n\n## Getting Started\n\nThe `openjson_function.sql` file found in the root of this repository contains a `T-SQL` script that demonstrates how to use the `OPENJSON` function in `Microsoft SQL Server 2016 and above`. \nThe `xml_function.sql` file found in the root of this repository contains a `T-SQL` script that demonstrates how to use the `XML` functions in `Microsoft SQL Server 2014`. \n\nThe query was created as an answer for a question on [Stack Overflow](https://stackoverflow.com/) on `09/14/22` that I answered called [How to perform a two column split by linking your data in sql server](https://stackoverflow.com/questions/73575888/how-to-perform-a-two-column-split-by-linking-your-data-in-sql-server).\n\nI hope you find this example useful and it helps you learn how to use `OPENJSON` in your own SQL queries.\nFeel free to reference the [Fiddle](https://dbfiddle.uk/yEGssKaq) I created to help answer the question.\n\n### Question\n\nMy db is on SQL server\n\nI have a situation where I have a column that brings me the phase of my card and a column that brings me the date that this card entered the phase, but they are in the format of an \"Array\". How can I link the phase name with its entry date via query?\n\n\n| card_id  | phase_history  | firstTimeIn   |\n| -------- | -------------- | -------------- \n| 8837     | [Start, Compliance, Contact, Down]|[2022-08-11T13:44:24+00:00, 2022-08-11T13:44:25+00:00, 2022-08-25T17:37:19+00:00, 2022-08-11T13:44:26+00:00]|\n| 6596     | [Start, Compliance, Contact, Down]|[2022-03-11T13:44:24+00:00, 2022-04-11T13:44:25+00:00, 2022-04-25T17:37:19+00:00, 2022-04-11T13:44:26+00:00]\n| 2416     | [Start, Contact, Up]|[2022-08-02T02:22:31+00:00, 2022-08-02T02:22:31+00:00, 2022-08-02T12:13:32+00:00]\n| 5424     | [Start, Compliance, Contact, Lead, Down]|[2022-09-01T12:51:24+00:00, 2022-09-01T12:51:25+00:00, 2022-09-01T13:25:52+00:00, 2022-09-01T12:51:26+00:00, 2022-09-01T16:47:31+00:00]\n\n\nI would like it to be like this:\n\n| card_id  | phase_history  | firstTimeIn   |\n| -------- | -------------- | --------------|\n|8837\t|Start|2022-08-11T13:44:24+00:00|\n|8837|Compliance|2022-08-11T13:44:25+00:00|\n\nIf anyone has any other suggestions on how to handle this I would appreciate it.\n\n### My Answer\n\nYou can use `OPENJSON` to convert the array rows into new rows by the `card_id` column, and use `TRIM` to remove any extraneous brackets and whitespaces. \n\n    /*  For SQL Server 2016 (compatibility level 130+) and higher */\n    SELECT d.card_id, a.phase_history, a.firstTimeIn\n    FROM cards d\n    CROSS APPLY (\n       SELECT \n       TRIM('[ ]' FROM c.[value]) AS phase_history, \n       TRIM('[ ]' FROM s.[value]) AS firstTimeIn\n       FROM OPENJSON(CONCAT('[\"', REPLACE(d.phase_history, ',', '\",\"'), '\"]')) c\n       LEFT OUTER JOIN OPENJSON(CONCAT('[\"', REPLACE(d.firstTimeIn, ',', '\",\"'), '\"]')) s \n          ON c.[key] = s.[key]\n    ) a \n    WHERE a.phase_history IN ('Start', 'Compliance')\n    AND card_id = 8837\n\n**Result Set:**\n\n|card_id\t| phase_history\t| firstTimeIn               |\n|-----------|---------------|---------------------------|\n|8837\t    |Start\t        | 2022-08-11T13:44:24+00:00 |\n|8837\t    |Compliance\t    | 2022-08-11T13:44:25+00:00 |\n\nThe real solution, *however*, would be to adjust your database design. Storing multiple values in an array format  will cause you a lot of problems in the future. Fixing it now rather than later will prevent future headaches. \n\ndb\u003c\u003efiddle [here][1].\n\n_Update_\n\nI've been recently asked to do this with an older version of SQL Server (SQL Server 2014). Because `OPENJSON` is only available in [SQL Server 2016 (compatibility level 130 or higher)][2], you should use a combination of `XML` functions, `CTEs`, and `CROSS APPLY` to achieve the same results as above. \n\n    /*  For SQL Server 2014 */\n    WITH PhaseHistoryCTE AS (\n        SELECT \n            d.card_id,\n            LTRIM(RTRIM(x.value('.', 'VARCHAR(50)'))) AS phase_history,\n            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn\n        FROM \n            cards d\n        CROSS APPLY (\n            SELECT CAST('\u003cx\u003e' + REPLACE(SUBSTRING(d.phase_history, 2, LEN(d.phase_history) - 2), ',', '\u003c/x\u003e\u003cx\u003e') + '\u003c/x\u003e' AS XML) AS xmlValues\n        ) AS a\n        CROSS APPLY xmlValues.nodes('/x') AS SplitLoad(x)\n    ),\n    FirstTimeInCTE AS (\n        SELECT \n            d.card_id,\n            LTRIM(RTRIM(x.value('.', 'VARCHAR(50)'))) AS firstTimeIn,\n            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn\n        FROM \n            cards d\n        CROSS APPLY (\n            SELECT CAST('\u003cx\u003e' + REPLACE(SUBSTRING(d.firstTimeIn, 2, LEN(d.firstTimeIn) - 2), ',', '\u003c/x\u003e\u003cx\u003e') + '\u003c/x\u003e' AS XML) AS xmlValues\n        ) AS b\n        CROSS APPLY xmlValues.nodes('/x') AS SplitBOL(x)\n    )\n    SELECT \n        p.card_id, \n        p.phase_history, \n        f.firstTimeIn\n    FROM \n        PhaseHistoryCTE p\n    LEFT OUTER JOIN \n        FirstTimeInCTE f\n    ON \n        p.rn = f.rn\n    WHERE \n        p.phase_history IN ('Start', 'Compliance')\n    AND \n        p.card_id = 8837;\n\ndb\u003c\u003efiddle [here][3].\n\n  [1]: https://dbfiddle.uk/yEGssKaq\n  [2]: https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16\n  [3]: https://dbfiddle.uk/Py0vD6Zf\n\n## Resources\n\n- [Stack Overflow](https://stackoverflow.com/)\n- [How to perform a two column split by linking your data in sql server](https://stackoverflow.com/questions/73575888/how-to-perform-a-two-column-split-by-linking-your-data-in-sql-server)\n- [Answer Example Fiddle](https://dbfiddle.uk/yEGssKaq)\n- [Microsoft SQL Server - 2022 Home](https://www.microsoft.com/en-us/sql-server/sql-server-2022)\n- [Microsoft SQL Server - 2022 Documentation](https://learn.microsoft.com/en-us/sql/sql-server/?view=sql-server-ver16)\n- [Microsoft SQL Server - Downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)\n- [Microsoft SQL Server - OPENJSON](https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16)\n- [Microsoft Excel](https://www.microsoft.com/en-us/microsoft-365/excel)\n- [JSON](https://www.json.org/json-en.html)\n- [JSON - Wikipedia](https://en.wikipedia.org/wiki/JSON)\n- [JSON - RFC 8259](https://tools.ietf.org/html/rfc8259)\n\n## License\n\nThis project is released under the terms of **The Unlicense**, which allows you to use, modify, and distribute the code as you see fit. \n- [The Unlicense](https://choosealicense.com/licenses/unlicense/) removes traditional copyright restrictions, giving you the freedom to use the code in any way you choose.\n- For more details, see the [LICENSE](LICENSE) file in this repository.\n\n## Credits\n\n**Author:** [Scott Grivner](https://github.com/scottgriv) \u003cbr\u003e\n**Email:** [scott.grivner@gmail.com](mailto:scott.grivner@gmail.com) \u003cbr\u003e\n**Website:** [linktr.ee/scottgriv](https://www.linktr.ee/scottgriv) \u003cbr\u003e\n**Reference:** [Main Branch](https://github.com/scottgriv/sql-mssql_openjson_example) \u003cbr\u003e\n\n---------------\n\n\u003cdiv align=\"center\"\u003e\n    \u003ca href=\"https://linktr.ee/scottgriv\" target=\"_blank\"\u003e\n        \u003cimg src=\"./docs/images/footer.png\" width=\"100\" height=\"100\"/\u003e\n    \u003c/a\u003e\n\u003c/div\u003e\n\n\u003c!-- End README --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscottgriv%2Fsql-mssql_openjson_example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fscottgriv%2Fsql-mssql_openjson_example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscottgriv%2Fsql-mssql_openjson_example/lists"}