1

I'm inserting data into a table using data from a JSON-file. I want to set a bit column isMain to 1 at the same time. I tried so by using the code below, but it throws an error saying it's incorrect syntax. How could I achieve this?

INSERT INTO Company
(
    OrganizationNumber,
    Name
    IsMain
)
SELECT company.*
FROM OPENROWSET(BULK '<path to json-file>', SINGLE_NCLOB) AS j
CROSS APPLY OPENJSON(BulkColumn)
WITH (
    organizationNumber NVARCHAR(255) '$.organizationNumber',
    name NVARCHAR(255) '$.name',
    isMain BIT '1'
)
AS company;
1
  • Define IsMain in your SELECT, not your OPENJSON's WITH clause. (SELECT organizationNumber, [name], 1 FROM...) Commented Jan 6, 2022 at 9:53

1 Answer 1

1

try this:

declare @json nvarchar(max)
declare @tmp as table(organizationNumber varchar(20),name varchar(20),IsMain bit)

set @json=N'{
   "data":[
      {
         "organizationNumber":"3888690",
         "name":"bob smith"
      }
   ]
}';



insert into @tmp
(
organizationNumber,
name,
IsMain
)
select 
  JSON_VALUE(c.value,'$.organizationNumber') as organizationNumber, 
 JSON_VALUE(c.value,'$.name') as name,
 1
  from OPENJSON(@json,'$.data') as c

select * from @tmp  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.