DEV Community

Cover image for How to import json to SQL
Flavio Campelo
Flavio Campelo

Posted on

How to import json to SQL

📮 Contact 🇧🇷 🇺🇸 🇫🇷

Twitter
LinkedIn


Declaring a variable with json content

Json content:

[
  {
    "name": "Flavio",
    "code": "FLA-1",
    "isDeleted": false
  },
  {
    "name": "Contoso",
    "code": "CON-1",
    "isDeleted": true
  }
]
Enter fullscreen mode Exit fullscreen mode
-- SET JSON CONTENT TO A VARIABLE (@JSON)...
DECLARE @json NVARCHAR(max) = N'[
    {
      "name": "Flavio",
      "code": "FLA-1",
      "isDeleted": false
    },
    {
      "name": "Contoso",
      "code": "CON-1",
      "isDeleted": true
    }
  ]';
Enter fullscreen mode Exit fullscreen mode

Fill a temp table with json content

-- FILL #TEMP TABLE WITH JSON CONTENT...
SELECT firstName, code, IIF(isDeleted = 1, 0, 1) as active 
    INTO #temp
    FROM OPENJSON(@json)
WITH  (
        firstName   VARCHAR(50) '$.name', 
        code        VARCHAR(10) '$.code',
        isDeleted   BIT         '$.isDeleted'
    );
Enter fullscreen mode Exit fullscreen mode

Show items from temp table

-- SHOW ITEMS FROM #TEMP TABLE
SELECT * FROM #temp;
Enter fullscreen mode Exit fullscreen mode

img1

If you need to drop temp table

-- REMOVE A #TEMP TABLE...
DROP TABLE #temp;
Enter fullscreen mode Exit fullscreen mode

Typos or suggestions?

If you've found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. If you feel comfortable with github, instead of posting a comment, please go directly to https://github.com/campelo/documentation and open a new pull request with your changes.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay