Skip to content
Advertisement

EF Core Insert operation – how does the SQL command work?

How does the following SQL command works?

exec sp_executesql N'SET NOCOUNT ON;
DECLARE @inserted0 TABLE ([Id] int, [_Position] [int]);
MERGE [OrderLine] USING (
VALUES (@p1, @p2, 0),
(@p3, @p4, 1),
(@p5, @p6, 2),
(@p7, @p8, 3)) AS i ([Item], [OrderId], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([Item], [OrderId])
VALUES (i.[Item], i.[OrderId])
OUTPUT INSERTED.[Id], i._Position
INTO @inserted0;

SELECT [t].[Id] FROM [OrderLine] t
INNER JOIN @inserted0 i ON ([t].[Id] = [i].[Id])
ORDER BY [i].[_Position];

',N'@p1 nvarchar(64),@p2 int,@p3 nvarchar(64),@p4 int,@p5 nvarchar(64),@p6 int,@p7 nvarchar(64),@p8 int',@p1=N'Item-1',@p2=1,@p3=N'Item-2',@p4=1,@p5=N'Item-3',@p6=1,@p7=N'Item-4',@p8=1

(It was generated by EF Core and it inserts some OrderLine entities).

Edit:
I understand the declaring of the TABLE type variable and have basic idea of MERGE operation. But having a hard time understanding how and when actually data gets inserted in the OrderLine table.

Advertisement

Answer

how and when actually data gets inserted in the OrderLine table.

The operative bit is ON 1=0

Which means rows are never matched, and so every row goes to

WHEN NOT MATCHED THEN
INSERT ([Item], [OrderId])
VALUES (i.[Item], i.[OrderId])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement