Oren A
Oren A

Reputation: 5880

SQL Server append query

I have the following (not working) query:

insert into [MyDB].[dbo].[Reports_StepsStat]  
    (ActivityID,TaskID,StepIndex,StepStatus,TimeSpanInSeconds,Score)
VALUES (
  SELECT
    tasks.ActivityID as ActivityID,
    tasks.ID as TaskID,
    [StepIndex]=item.value('(StepIndex)[1]', 'NVARCHAR(MAX)'),
    [StepStatus]=item.value('(Status)[1]', 'NVARCHAR(MAX)'),
    [TimeSpanInSeconds] = DATEDIFF(MINUTE, item.value('(StartedOn)[1]',    'datetime'),item.value('(FinishedOn)[1]', 'datetime')),
    tasks.Score as Score
  FROM 
    [MyDB].[dbo].[Tasks] as tasks 
  CROSS APPLY 
    [Progress].nodes ('//Progress/Steps/ProgressStep') Progress(item)
)  

The inner select query (SELECT task.ActivityID..) works perfectly and produces the expected table.

The outer insert into part is supposed to append the result of the inner part to a table by the name of Reports_StepsStat. This does not work.

I have tried and succeeded doing that with SELECT INTO, but apparently SELECT INTO can only be used to create a new table, and not to append to an existing table, which is what I need.

The errors I get are:

Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.

Upvotes: 1

Views: 17164

Answers (2)

Yogendra Singh
Yogendra Singh

Reputation: 34367

I think VALUES ( is not required in your query.

 insert into [MyDB].[dbo].[Reports_StepsStat]  
 (ActivityID,TaskID,StepIndex,StepStatus,TimeSpanInSeconds,Score)
 SELECT
  tasks.ActivityID as ActivityID,
  tasks.ID as TaskID,
  [StepIndex]=item.value('(StepIndex)[1]', 'NVARCHAR(MAX)'),
  [StepStatus]=item.value('(Status)[1]', 'NVARCHAR(MAX)'),
  [TimeSpanInSeconds]=DATEDIFF(MINUTE,item.value('(StartedOn)[1]', 'datetime'),
  item.value('(FinishedOn)[1]', 'datetime')),
  tasks.Score as Score
 FROM [MyDB].[dbo].[Tasks] as tasks 
     CROSS APPLY [Progress].nodes ('//Progress/Steps/ProgressStep') Progress(item)

Upvotes: 6

pbhd
pbhd

Reputation: 4467

Syntax is

insert into a select * from b

so just omit the values (...) surroundng the select...

Upvotes: 3

Related Questions