Can we Store JSON data as varbinary in SQL server?

Dev_Fuel07 21 Reputation points
2022-04-04T05:34:48.323+00:00

I am only creating a staging table to temporary work with JSON data in memory, therefore avoiding it to store in a column per field manner. Instead I would like to store that variable json values in SQL DB entity. I am stuck how to store it?

I am using .Net Framework - C# MVC - EntityFramework 6.2

By Default Entity Framework will generate nvarchar(max) type for JSON string but I have observed that nvarchar(max) will not retrieve all data only a limited chunk of it and that will lead to JSON deserialization failure in memory.

I want to avoid this and store large JSON data as varbinary, JSON object will have 200 fields (key value pairs) some of them might hold more than 500 alphanumeric characters.

How to set datatype for such scenario from entity framework code first approach, Any suggestions?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,375 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,714 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
{count} votes

Accepted answer
  1. Olaf Helper 40,816 Reputation points
    2022-04-04T05:51:24.503+00:00

    Sure you can store JSON as varbinary; but that don't make much sense. JSON is string and so nvarchar(max) is the better choice.
    All JSON functions in T-SQL work with nvarchar, not with binary, see https://learn.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server?view=sql-server-ver15

    but I have observed that nvarchar(max) will not retrieve all data only a limited chunk of it

    Then you are doing something wrong, it works for me and all others.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 101K Reputation points MVP
    2022-04-04T21:31:13.28+00:00

    If you store the data as nvarchar(MAX) there should be any problem in retrieving it. But I seem to recall that there is an issue if you use FOR JSON PATH. Then you need to retrieve the JSON with a stream reader, of which I do not recall the details.

    But you can work around this by saying:

    SET @json = (SELECT ... FOR JSON PATH)
    SELECT @json AS MyJson
    
    1 person found this answer helpful.
    0 comments No comments