version is:
Microsoft SQL Server 2008 R2 (SP1) - 10.50.2811.0 (X64) Apr 6 2012 01:59:29 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)
I'm just playing around with the merge statement to see if i can get it to work on a CTE that includes computed fields/constants/groupings and aggregates. And yes it does! BUT it craps itself if you try to look at the output clause
Has anybody come across this or have a way around it? anyone on later versions of 2k8r2 or 2012 that can give it a test?
create table #src (id int, val decimal(18,9)) go create table #dest (id int, val decimal(18,9)) go -- ignore complexity, i was trying to test something else when i noticed this issue... this is just generating 10 rows with a random decimal value insert into #src SELECT top 10 ROW_NUMBER() over (order by getdate()) ,right(reverse(stuff(reverse(abs(cast(CAST(NEWID() AS varbinary) as bigint))),10,1,'.')),13) FROM sysobjects -- merge here -- first cte that generates the aggregate ;with cte as (select id, SUM(val) val from #dest group by id) -- 2nd cte that we use as the target ,cte2 as (select x.*, cte.val AS summedval from #dest x inner join cte on x.id = cte.id) MERGE cte2 AS Target USING #src as Source ON (Target.id = Source.id) WHEN NOT MATCHED BY TARGET THEN INSERT (id, val) values (Source.id, Source.Val) WHEN MATCHED AND Target.summedVal <> source.val THEN update SET val = 1 OUTPUT INSERTED.id,inserted.val;
Works fine without the output clause. Add the output clause and get booted/disconnected with the following message:
Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.