Search code examples
sqlsql-serversql-insert

How can I add a row in a table created by a query in SQL Server?


I a beginner with SQL. I first wrote a query which created a table. With this table I would like to add some rows. I thought that using "insert into" statement was the right idea, but it did not work.

insert into (
    select Element = [Key]
          ,New = max(case when time_index=1 then value end)
          ,'Current' = max(case when time_index>=2 then value end)
     From  (
            Select [time_index]
                  ,B.*
             From  (select * from ifrs17.output_bba where id in (602677,602777)) A
             Cross Apply (
                          Select [Key]
                                ,Value
                           From OpenJson( (Select A.* For JSON Path,Without_Array_Wrapper ) )
                           Where [Key] not in ('time_index')
                         ) B
            ) A
     Group By [Key])
 values ('acc_test','test', 'test')

I receive this error message:

Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'select'. Msg 156, Level 15, State 1, Line 17 Incorrect syntax near the keyword 'values'.

How can I add rows to my table?


Solution

  • Use UNION ALL to join the query and a row value constructs by elements:

    insert into (
        select Element = [Key]
              ,New = max(case when time_index=1 then value end)
              ,'Current' = max(case when time_index>=2 then value end)
         From  (
                Select [time_index]
                      ,B.*
                 From  (select * from ifrs17.output_bba where id in (602677,602777)) A
                 Cross Apply (
                              Select [Key]
                                    ,Value
                               From OpenJson( (Select A.* For JSON Path,Without_Array_Wrapper ) )
                               Where [Key] not in ('time_index')
                             ) B
                ) A
         Group By [Key])
    UNION
    SELECT 'acc_test', 'test', 'test'