简体   繁体   中英

How to INSERT getDate() into a column in a table which also has columns that have data inserted with OPENJSON and CROSSAPPLY

I have a the following JSON that needs to get inserted into a table

{
    "Parent": {       
            "level": "Ground",           
        },
     "Items":[
              { "name" : "name1",
                "id" : "id1"
              },
              { "name" : "name2",
                "id" : "id2"
              },
           ]

}

This is the query i wrote for inserting into the table

Insert into table(name,id,level,dateInserted) Select(name,id,level,dateInserted)FROM OPENJSON((select 
* from @json), N'$.Items')
    WITH (  id   nvarchar(max) N'$.id',
        name   nvarchar(max) N'$.name')
   CROSS APPLY OPENJSON((select * from @json), N'$.Parent')
        WITH( level nvarchar(max) N'$.level'))
 **CROSS APPLY dateInserted dateTime getDate()**

I am having issue inserting getDate() into the dateInserted column. As dateInserted is something that is not being read from the JSON itself, I am having trouble inserting it into the table. What is the right way to do it?

It was a silly mistake. It has nothing to do with the OPENJSON or CROSS APPLY For anyone looking for an answer

Insert into table(name,id,level,dateInserted) Select(name,id,level,getDate())FROM 
OPENJSON((select 
* from @json), N'$.Items')
WITH (  id   nvarchar(max) N'$.id',
    name   nvarchar(max) N'$.name')
CROSS APPLY OPENJSON((select * from @json), N'$.Parent')
    WITH( level nvarchar(max) N'$.level'))

The getDate() has to be inside the Select clause

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM